I checked this backend code using Postman. It sometimes works properly. But, sometimes, it does not work. What's the matter with this code?

Viewed 70

I checked this backend code using Postman. It sometimes works properly. But, sometimes, it does not work. What's the matter with this code?

I used the technology koa.js. I create dao file, api file, and router file to handle the backend.

studentRouter.put("/:id", async ctx=>{
    var ObjectID = require('mongodb').ObjectId;
    var id = new ObjectID(ctx.params.id);
    let student = ctx.request.body;
    student =  updateStudent(id,student);
    ctx.set('Context-Type','application/json' );
    ctx.body = {success:true, existingData:student}
    ctx.status = 200;
})
1 Answers

In the router file, please use the await ' keyword before these functions

addStudent()
getStudents()
getStudent()
updateStudent()
deleteStudent()

As an example

studentRouter.post("/",async ctx =>{
    const data = ctx.request.body;
    const post = await addStudent(data);
    ctx.set('Content-Type','application/json');
    ctx.body = {success:true}
    ctx.status = 201;
})
Related