如何使用Koa ctx正文进行多个响应?

JavaScript KoaJS

樱小胖Mandy

2020-04-07

我是koa和postgresql的新用户。我创建了一个用户登录api,但出现404 not found错误。我的查询和检查正在按我在控制台上检查的方式工作,但ctx.body无法正常工作。我如何使用Koa ctx.body处理多个响应?不知道为什么ctx.body无法正常工作。我们如何解决这个问题?希望你理解我的问题。


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",
                    }
                }
            });
      }
});

第4151篇《如何使用Koa ctx正文进行多个响应?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

0个回答

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android