reactjs – I’m having errors in both backend and frontend. Koa & React

When I’m going to run the code it gives the following error. npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! react-app@1.0.0 start: webpack-dev-server --mode development --open --hot --port 3000
npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the react-app@1.0.0 start script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

I reinstalled the nodemodules. But couldn’t solve it.

//server.js
require("dotenv").config();
const Koa = require("koa");
const KoaRouter = require("koa-router");
const cors = require("@koa/cors");
const bodyParser = require("koa-bodyparser");
const json = require("koa-bodyparser");
const { dbConnect } = require("./utils/dbConnect");
const courseRoutes = require("./routes/course.routes");
const studentRoutes = require("./routes/student.routes");

const app = new Koa();
const router = new KoaRouter();

app.use(cors());
app.use(bodyParser());
app.use(json());
app.use(router.routes()).use(router.allowedMethods());
app.use(courseRoutes.routes());
app.use(studentRoutes.routes());

router.get("/", (ctx) => {
  ctx.body = { message: "Student Management API" };
});

app.listen(9000, () => {
  dbConnect();
  console.log(`Server is up and running on http://localhost:9000`);
});

//dbConnect
const mongoose = require("mongoose");

const dbConnect = () => {
  const dbConStr = process.env.MONGODB_URL;

  mongoose.connect(dbConStr, () => {
    console.log("Database connected");
  });
};

module.exports = { dbConnect };

//course.routes
const KoaRouter = require("koa-router");
const router = new KoaRouter({ prefix: "/course" });
const {
  addCourse,
  getCourses,
  updateCourse,
  deleteCourse,
} = require("../controller/course.controller");

router.post("/add", addCourse);
router.delete("/:courseId", deleteCourse);
router.put("/:courseId", updateCourse);
router.get("/", getCourses);

module.exports = router;

//student.routes
const KoaRouter = require("koa-router");
const {
  addStudent,
  getStudents,
  updateStudent,
  deleteStudent,
} = require("../controller/student.controller");
const router = new KoaRouter({ prefix: "/student" });

router.post("/add", addStudent);
router.delete("/:studentId", deleteStudent);
router.put("/:studentId", updateStudent);
router.get("/", getStudents);

module.exports = router;

//course.models
const mongoose = require("mongoose");

const CourseSchema = new mongoose.Schema({
  courseName: { type: String, required: true },
  courseFee: { type: Number, required: true },
  students: [{ type: mongoose.Schema.Types.ObjectId, required: false, ref: "students" }],
});

const Course = mongoose.model("courses", CourseSchema);

module.exports = Course;

//student.models
const mongoose = require("mongoose");

const StudentSchema = new mongoose.Schema({
  name: { type: String, required: true },
  nic: { type: String, required: true },
  age: { type: Number, required: true },
  courseId: { type: mongoose.Schema.Types.ObjectId, required: false, ref: "courses" },
});

const Student = mongoose.model("students", StudentSchema);

module.exports = Student;

//course.controller
const Course = require("../models/course.model");

const addCourse = async (ctx) => {
  try {
    const { courseName, courseFee, students } = ctx.request.body;

    const course = await Course.create({
      courseName: courseName,
      courseFee: courseFee,
      students: students,
    });

    return (ctx.body = course);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};

const getCourses = async (ctx) => {
  try {
    const courses = await Course.find({}).populate({ path: "students", select: "name nic age" });
    return (ctx.body = courses);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};

const updateCourse = async (ctx) => {
  try {
    const courseId = ctx.params.courseId;

    const { courseName, courseFee, students } = ctx.request.body;
    const course = await Course.findByIdAndUpdate(courseId, {
      courseName: courseName,
      courseFee: courseFee,
      students: students,
    });
    return (ctx.body = course);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};

const deleteCourse = async (ctx) => {
  try {
    const courseId = ctx.params.courseId;
    const course = await Course.findByIdAndDelete(courseId);
    return (ctx.body = course);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};

module.exports = {
  addCourse,
  getCourses,
  updateCourse,
  deleteCourse,
};

//student.controller
const Student = require("../models/student.model");
const Course = require("../models/course.model");

const addStudent = async (ctx) => {
  try {
    const { name, nic, age, courseId } = ctx.request.body;
    const student = await Student.create({
      name,
      nic,
      age,
      courseId,
    });

    await Course.findByIdAndUpdate(courseId, { $push: { students: student._id } });
    return (ctx.body = student);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};

const getStudents = async (ctx) => {
  try {
    const students = await Student.find().populate({
      path: "courseId",
      select: "courseName courseFee",
    });
    return (ctx.body = students);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};

const updateStudent = async (ctx) => {
  try {
    const studentId = ctx.params.studentId;
    const { name, nic, age, courseId } = ctx.request.body;

    const student = await Student.findByIdAndUpdate(studentId, {
      name,
      nic,
      age,
      courseId,
    });

    await Course.findByIdAndUpdate(student.courseId, {
      $pull: { students: studentId },
    });

    await Course.findByIdAndUpdate(courseId, {
      $push: { students: studentId },
    });

    return (ctx.body = student);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};

const deleteStudent = async (ctx) => {
  try {
    const studentId = ctx.params.studentId;

    const student = await Student.findById(studentId);

    await Course.findByIdAndUpdate(student.courseId, { $pull: { students: studentId } });
    await Student.findByIdAndDelete(studentId);
    return (ctx.body = student);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};

module.exports = {
  addStudent,
  getStudents,
  updateStudent,
  deleteStudent,
};

//.env
MONGODB_URL=mongodb://localhost:27017/managementdb

//package.json
{
  "name": "af-koa-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon src/index.js",
    "start": "node src/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@koa/cors": "^3.3.0",
    "dotenv": "^16.0.1",
    "koa": "^2.13.4",
    "koa-bodyparser": "^4.3.0",
    "koa-json": "^2.0.2",
    "koa-router": "^10.1.1",
    "mongoose": "^6.3.6"
  }
}

//react
//public>index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>AF React</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

//.env
BASE_URL=http://localhost:9000

//src
//pages>Course
import React, { useEffect, useState } from "react";
import axios from "axios";

const CoursePage = () => {
  const [courseName, setCourseName] = useState("");
  const [courseFee, setCourseFee] = useState("");
  const [courses, setCourses] = useState([]);
  const [isEditClick, setIsEditClick] = useState(false);
  const [editId, setEditId] = useState("");

  const [editName, setEditName] = useState("");
  const [editFee, setEditFee] = useState("");

  useEffect(() => {
    axios.get(`${process.env.BASE_URL}/course/`).then((res) => {
      setCourses(res.data);
    });
  }, []);

  const saveData = (e) => {
    e.preventDefault();
    const courseObj = {
      courseName,
      courseFee,
    };

    axios
      .post(`${process.env.BASE_URL}/course/add`, courseObj)
      .then((res) => {
        alert("Data added");
        axios.get(`${process.env.BASE_URL}/course/`).then((res) => {
          setCourses(res.data);
        });
        setCourseName("");
        setCourseFee("");
      })
      .catch((err) => {
        alert(err.message);
      });
  };

  const updateData = (e) => {
    e.preventDefault();
    const courseObj = {
      courseName: editName,
      courseFee: editFee,
    };
    console.log(courseObj);

    axios
      .put(`${process.env.BASE_URL}/course/${editId}`, courseObj)
      .then((res) => {
        alert("Course Updated");
        axios.get(`${process.env.BASE_URL}/course/`).then((res) => {
          setCourses(res.data);
        });
        setIsEditClick(false);
      })
      .catch((err) => {
        alert(err.message);
      });
  };

  const deleteCourse = (e) => {
    e.preventDefault();
    axios
      .delete(`${process.env.BASE_URL}/course/${e.target.id}`)
      .then(() => {
        axios.get(`${process.env.BASE_URL}/course/`).then((res) => {
          setCourses(res.data);
        });
      })
      .catch((err) => {
        alert(err.message);
      });
  };

  const onEditClick = (e) => {
    e.preventDefault();
    setEditId(e.target.id);
    setIsEditClick(!isEditClick);

    const course = courses.find((course) => course._id === e.target.id);
    setEditName(course.courseName);
    setEditFee(course.courseFee);
  };

  return (
    <div>
      <h1>Course Page</h1>
      <div>
        <input
          type="text"
          placeholder="Enter course name"
          value={courseName}
          style={{ margin: 5 }}
          onChange={(e) => setCourseName(e.target.value)}
        />
        <input
          type="number"
          placeholder="Enter course free"
          value={courseFee}
          style={{ margin: 5 }}
          onChange={(e) => setCourseFee(e.target.value)}
        />
        <button onClick={(e) => saveData(e)} style={{ margin: 5 }}>
          Submit
        </button>
        <br />

        <table>
          <tr>
            <th>Course Name</th>
            <th>Course Fee</th>
            <th>Actions</th>
          </tr>
          {courses &&
            courses.length > 0 &&
            courses.map((course, index) => (
              <tr key={index}>
                <td>
                  {isEditClick && course._id === editId ? (
                    <input
                      type="text"
                      value={editName}
                      onChange={(e) => setEditName(e.target.value)}
                    />
                  ) : (
                    course.courseName
                  )}
                </td>
                <td>
                  {isEditClick && course._id === editId ? (
                    <input
                      type="number"
                      value={editFee}
                      onChange={(e) => setEditFee(e.target.value)}
                    />
                  ) : (
                    course.courseFee
                  )}
                </td>
                <td>
                  <button id={course._id} onClick={(e) => onEditClick(e)}>
                    {isEditClick && course._id === editId ? "Cancel" : "Update"}
                  </button>
                  {isEditClick && course._id === editId && (
                    <button onClick={(e) => updateData(e)}>Save</button>
                  )}
                  <button id={course._id} onClick={(e) => deleteCourse(e)}>
                    Delete
                  </button>
                </td>
              </tr>
            ))}
        </table>
      </div>
    </div>
  );
};

export default CoursePage;

//pages>Home
import React from "react";
import { Link } from "react-router-dom";

const Home = () => {
  return (
    <div>
      <Link to="student">
        <button>Manage Students</button>
      </Link>
      <Link to="course">
        <button>Manage Courses</button>
      </Link>
    </div>
  );
};

export default Home;

//pages>Student
import React, { useEffect, useState } from "react";
import axios from "axios";

const StudentPage = () => {
  const [name, setName] = useState("");
  const [nic, setNIC] = useState("");
  const [age, setAge] = useState("");
  const [courseId, setCourseId] = useState("");

  const [students, setStudents] = useState([]);
  const [courses, setCourses] = useState([]);

  const [isEditClick, setIsEditClick] = useState(false);
  const [editName, setEditName] = useState("");
  const [editNIC, setEditNIC] = useState("");
  const [editAge, setEditAge] = useState("");
  const [editCourseId, setEditCourseId] = useState("");

  useEffect(() => {
    axios.get(`${process.env.BASE_URL}/course/`).then((res) => {
      setCourses(res.data);
    });
    axios.get(`${process.env.BASE_URL}/student/`).then((res) => {
      setStudents(res.data);
    });
  }, []);

 
  const addStudent = (e) => {
    e.preventDefault();
  };

  const updateStudent = (e) => {
    e.preventDefault();
  };

  const deleteStudent = (e) => {
    e.preventDefault();
  };

  const onEditClick = (e) => {
    e.preventDefault();
    const student = students.find((student) => {
      student._id === e.target.id;
    });
    if (student) {
      setEditName(student.name);
      setEditAge(student.age);
      setEditNIC(student.nic);
      setIsEditClick(true);
    }
  };

  return (
    <div>
      <h1>Student Page</h1>
      <div style={{ marginBottom: 5 }}>
        <input
          type="text"
          placeholder="Enter name"
          value={name}
          style={{ margin: 5 }}
          onChange={(e) => setName(e.target.value)}
        />
        <input
          type="text"
          placeholder="Enter nic"
          value={nic}
          style={{ margin: 5 }}
          onChange={(e) => setNIC(e.target.value)}
        />
        <input
          type="number"
          placeholder="Enter age"
          value={age}
          style={{ margin: 5 }}
          onChange={(e) => setAge(e.target.value)}
        />
        <select onChange={(e) => setCourseId(e.target.value)}>
          {courses &&
            courses.length > 0 &&
            courses.map((course, index) => (
              <option value={course._id} key={index}>
                {course.courseName}
              </option>
            ))}
        </select>
        <button onClick={(e) => addStudent(e)} style={{ margin: 5 }}>
          Submit
        </button>
      </div>

      <table>
        <tr>
          <th>Name</th>
          <th>NIC</th>
          <th>Age</th>
          <th>Course</th>
          <th>Actions</th>
        </tr>
        {students &&
          students.length > 0 &&
          students.map((student, index) => (
            <tr key={index}>
              <td>{student.name}</td>
              <td>{student.nic}</td>
              <td>{student.age}</td>
              <td>{student.courseId && student.courseId.courseName}</td>
            </tr>
          ))}
      </table>
    </div>
  );
};

export default StudentPage;

//App.js
import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import CoursePage from "./pages/Course";
import Home from "./pages/Home";
import StudentPage from "./pages/Student";

const App = () => {
  return (
    <div>
      <Router>
        <Routes>
          <Route path="/student" element={<StudentPage />} />
          <Route path="/course" element={<CoursePage />} />
          <Route path="/" element={<Home />} />
        </Routes>
      </Router>
    </div>
  );
};

export default App;

//index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

ReactDOM.render(<App />, document.getElementById("root"));

//webpack.config.js
const path = require("path");
const { DefinePlugin } = require("webpack");
const dotenv = require("dotenv");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: "./src/index.js",
  output: {
    path: path.join(__dirname, "/build"),
    filename: "index.js",
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./public/index.html",
    }),
    new DefinePlugin({
      "process.env": JSON.stringify(dotenv.config().parsed),
    }),
  ],
  devServer: {
    historyApiFallback: true,
  },
  module: {
    rules: [
      {
        test: /.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-env", "@babel/preset-react"],
          },
        },
      },
    ],
  },
};

//package.json
{
  "name": "af-react-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --mode development --open --hot --port 3000",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.27.2",
    "dotenv": "^16.0.1",
    "react": "^18.1.0",
    "react-dom": "^18.1.0",
    "react-router-dom": "^6.3.0"
  },
  "devDependencies": {
    "@babel/core": "^7.18.2",
    "@babel/preset-env": "^7.18.2",
    "@babel/preset-react": "^7.17.12",
    "babel-loader": "^8.2.5",
    "html-webpack-plugin": "^5.5.0",
    "webpack": "^5.73.0",
    "webpack-cli": "^4.9.2",
    "webpack-dev-server": "^4.9.2"
  }
}


Leave a Comment