5

I am new in node with koa and postgresql. I have a created a user login api but i'm getting 404 not found error. My queries and checks are working as i checked on console but ctx.body not working. How i can handle multiple responses with koa ctx.body? Don't know why no ctx.body is working. How we can solve this issue? Hope you understand my issue.


router.post('/userLogin', async (ctx) => {

    var email = ctx.request.body.email;
    var password = ctx.request.body.password;

    if (
        !email ||
        !password
    ) {
        ctx.response.status = 400;
        ctx.body = {
            status: 'error',
            message: 'Please fill all the fields'
        }
    } else {

        await ctx.app.pool.query("SELECT * FROM users WHERE email = $1",
            [`${email}`],
            async (err, result) => {
                if(err){
                    console.log(err);
                    throw err;
                }
                if (result) {
                   await bcrypt.compare(password, result.rows[0].password).then(function (res) {

                        if (res === true) {
                            ctx.body = {
                                status: 200,
                                message: "User login successfully",
                                data: result.rows[0],
                            };
                        }else{
                            ctx.body = {
                                status: 400,
                                message: "Incorrect password",
                            }
                        }
                    });
                }else{
                    ctx.body = {
                        status: 400,
                        message: "Invalid email",
                    }
                }
            });
      }
});
Nilanka Manoj
  • 3,527
  • 4
  • 17
  • 48
Daniyal Mughees
  • 303
  • 7
  • 21

1 Answers1

1

In regards to your 404 issue: HTTP 404 implies that your route does not exist yet. Please make sure your router.post('/userLogin') router is actually getting registered via app.use(router.routes()).

Refering to your question in regards to using ctx.body for multiple responses:

You can set ctx.body multiple times but only the last one will be used in the response.

For example:

ctx.body = 'Hello'
ctx.body = 'World'

This example will respond with World.

You can either concatenate your values in order to have them sent as one string/object, or use streaming where you control the read-stream-buffer. Check https://stackoverflow.com/a/51616217/1380486 and https://github.com/koajs/koa/blob/master/docs/api/response.md#responsebody-1 for documentation.

Steven
  • 1,052
  • 17
  • 30