Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to enable cros origin in koajs

how to enable cros origin in koajs

  • implement cors

    Access to XMLHttpRequest at ‘http://localhost:3000/course’ from origin ‘http://localhost:1234’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

>Solution :

npm init
npm i koa
npm i nodemon –save-dev
npm i @koa/router
npm i koa-bodyparser
npm i @koa/cors
npm i dotenv mongoose koa-json

paxkage.json

    {
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "start": "nodemon app.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@koa/cors": "^3.3.0",
    "@koa/router": "^10.1.1",
    "dotenv": "^16.0.1",
    "koa": "^2.13.4",
    "koa-bodyparser": "^4.3.0",
    "koa-json": "^2.0.2",
    "mongoose": "^6.4.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.18"
  }
}

connect db

MONGODB_URL = mongodb://localhost:27017/db 

const mongoose = require("mongoose");

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

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

module.exports = { dbConnect };

app.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-json");
const { dbConnect } = require("./src/utils/dbConnect");

const courseRoutes = require("./src/routes/course.routes");
const studentRouteres = require("./src/routes/student.routes");

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

app.use(
  cors({
    origin: "http://localhost:1234",
    credentials: true, //access-control-allow-credentials:true
    optionSuccessStatus: 200,
  })
);

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

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

app.listen(3000, () => {
  dbConnect();
  console.log("port-3000");
});

model class

const mongoose = require("mongoose");

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

const Course = mongoose.model("courses", courseSchema);
module.exports = Course;


const mongoose = require("mongoose");

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

const Student = mongoose.model("students", studentSchema);
module.exports = Student;

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 getCourse = async (ctx) => {
  try {
    const courses = await Course.find({}).populate({
      path: "students",
      select: "name age batch ",
    });
    return (ctx.body = courses);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};

const getAllCourse = async (ctx) => {
  try {
    const courses = await Course.find({});
    return (ctx.body = courses.data);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};

const getCourseById = async (ctx) => {
  try {
    const courseId = ctx.params.id;
    const courses = await Course.findById(courseId);
    return (ctx.body = courses);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};

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

    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.id;
    const course = await Course.findByIdAndDelete(courseId);
    return (ctx.body = course);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};

module.exports = {
  addCourse,
  getCourse,
  updateCourse,
  deleteCourse,
  getCourseById,
  getAllCourse,
};


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

const addStudent = async (ctx) => {
  try {
    const { name, age, batch, courseId } = ctx.request.body;

    const student = await Student.create({
      name,
      age,
      batch,
      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 student = await Student.find().populate({
      path: "courseId",
      select: "courseName courseFee",
    });
    return (ctx.body = student);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};

const getStudentById = async (ctx) => {
  try {
    const studentId = ctx.params.id;
    const student = await Student.findById(studentId);
    return (ctx.body = student);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};

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

    const { name, age, batch, courseId } = ctx.request.body;
    const student = await Student.findByIdAndUpdate(studentId, {
      name,
      age,
      batch,
      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.id;
    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,
  getStudentById,
};

roter

const KoaRouter = require("@koa/router");
const {
  addCourse,
  getCourse,
  updateCourse,
  deleteCourse,
  getCourseById,
  getAllCourse,
} = require("../controller/course.controller");
const router = new KoaRouter({ prefix: "/course" });

router.post("/add", addCourse);
router.get("/", getCourse);
router.get("/:id", getCourseById);
router.put("/:id", updateCourse);
router.delete("/:id", deleteCourse);

router.get("/all", getAllCourse);

module.exports = router;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading