Dan*_*ees 5 javascript postgresql node.js koa ctx
我是 koa 和 postgresql 节点的新手。我创建了一个用户登录 api,但收到 404 未找到错误。当我在控制台上检查时,我的查询和检查正在工作,但 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",
}
}
});
}
});
Run Code Online (Sandbox Code Playgroud)
关于您的 404 问题:HTTP 404 意味着您的路由尚不存在。请确保您的router.post('/userLogin')路由器实际上是通过 注册的app.use(router.routes())。
参考您关于使用ctx.body多个回复的问题:
您可以设置ctx.body多次,但响应中只会使用最后一次。
例如:
ctx.body = 'Hello'
ctx.body = 'World'
Run Code Online (Sandbox Code Playgroud)
此示例将响应World。
您可以连接您的值以便将它们作为一个字符串/对象发送,或者在您控制读取流缓冲区的情况下使用流式传输。检查/sf/answers/3613135221/和https://github.com/koajs/koa/blob/master/docs/api/response.md#responsebody-1以获取文档。
| 归档时间: |
|
| 查看次数: |
2158 次 |
| 最近记录: |