Search code examples
node.jsmongodbkoa

how to send response in koa.js with node


how to send response in koa.js with node? in below example I want to send the response with proper status code and message but below example didn't send anything.

    let user = await User.findOne({mobile:ctx.request.body.mobile});
    if(user){
        ctx.status = 400;
        ctx.message = "Already Exist";
    }else{
        let userData = await new User(ctx.request.body).save();
        ctx.status = 200;
        ctx.message = "User Registered Success"
    }

Solution

  • If you pass an object to ctx.body it will be returned as JSON:

    ctx.body = {
      status:  200,
      message: 'User Registered Successfully',
      data:    userData
    };