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

我是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",}
                }
            });
      }
});
kingdee624 回答:如何使用Koa ctx正文进行多个响应?

关于您的404问题: HTTP 404表示您的路由尚不存在。请确保您的router.post('/userLogin')路由器实际上是通过app.use(router.routes())注册的。

关于使用ctx.body进行多次答复,请参见您的问题:

您可以多次设置ctx.body,但响应中仅使用最后一个。

例如:

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

此示例将以World进行响应。

您可以连接值以使它们作为一个字符串/对象发送,也可以在控制读取流缓冲区的地方使用流。检查https://stackoverflow.com/a/51616217/1380486https://github.com/koajs/koa/blob/master/docs/api/response.md#responsebody-1以获得文档。

本文链接:https://www.f2er.com/2892628.html

大家都在问