0

I have a created a simple login api but i'm getting 404 error. How i can solve this issue? My ctx body is not working. When i hit on postman it throws not found.

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

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


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

                        if (res === true) {
                            ctx.body = {
                                status: 200,
                                message: "login successfully",
                                data: result.rows[0],
                            };
                        }else{
                            ctx.body = {
                                status: 400,
                                message: "Incorrect password! Try again.",
                            }
                        }
                    });
                }else{
                    ctx.body = {
                        status: 400,
                        message: "Invalid phone",
                    }
                }
            });
});
4

1 回答 1

2

首先不要将异步与回调 &then

利用const res = await somepromise()

您对查询使用了回调,then对 bcrypt.compare 使用了回调,而不是等待它

router.post('/login', async (ctx, next) => {
  const phone= ctx.request.body.phone;
  const password = ctx.request.body.password;
  const result =  await ctx.app.pool.query("SELECT * FROM users WHERE phone= $1",  [`${phone}`])

  if (result) {
     const pwCorrect = await bcrypt.compare(password, result.rows[0].password)
     if (pwCorrect === true) {
        ctx.body = {
           status: 200,
           message: "login successfully",
           data: result.rows[0],
        };
     }else{
         ctx.body = {
           status: 400,
           message: "Incorrect password! Try again.",
         }
     }
  } else{
      ctx.body = {
        status: 400,
        message: "Invalid phone",
      }

});
于 2019-12-19T18:11:15.357 回答