node.js - 当代码说返回 500 时,为什么这条快速路线返回 200 状态代码?
问题描述
我有这条路线预计会返回 500 状态代码。
/* Return all the users id */
router.post('/user/list', async function (req, res, next) {
const data = await scanAll(req.body.port, req.body.ip);
console.log("data ", data) //data 500
if (data === 500) {
res.json({
error: "Error, server connection refused"
}).status(500);
}
else if (data.length === 0) {
res.json(data).status(204)
} else {
res.json(data).status(200);
}
})
它扫描一个 redis 服务器并返回数据。
好吧,我的前端收到了错误的 json。但收到 200 状态码。邮递员也是如此
这怎么可能?
解决方案
根据 Express API:https ://expressjs.com/en/4x/api.html#res.status
您需要在致电status
前致电json
或send
res.status(400).send('Bad Request')
res.status(500).json({ error: "Error, server connection refused" })
参考示例,
- https://expressjs.com/en/4x/api.html#res.send
- https://expressjs.com/en/4x/api.html#res.json
- https://expressjs.com/en/4x/api.html#res.status
因此,将上面的代码段更改为,
/* Return all the users id */
router.post('/user/list', async function (req, res, next) {
const data = await scanAll(req.body.port, req.body.ip);
console.log("data ", data) //data 500
if (data === 500) {
res.status(500).json({
error: "Error, server connection refused"
});
}
else if (data.length === 0) {
res.status(204).json(data);
} else {
res.status(200).json(data);
}
})
推荐阅读
- javascript - 以角度拍摄最后一个位置html5 canvas js
- django - Django Heroku 没有名为“我的应用程序名称”的模块
- c++ - 为什么这个浮点比较会产生错误?
- python - python - 不支持的操作数类型
- c# - 使用 Visual Studio 2015 发送调整图片大小的电子邮件
- c++ - 使用 cmake 包含静态库
- angular - 如何在 Docker 映像创建过程中从 npm-install 过程中排除 @angular/cli?
- sql-server - 如何从 SQL Server 中检索已排序的分层数据
- java - 在 Eclipse Oxygen 上运行 GWT
- c# - 线程 0xc28 已退出,代码为 0