首页 > 解决方案 > 当代码说返回 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 状态码。邮递员也是如此

在此处输入图像描述

这怎么可能?

标签: node.jsexpress

解决方案


根据 Express API:https ://expressjs.com/en/4x/api.html#res.status

您需要在致电status前致电jsonsend

res.status(400).send('Bad Request')
res.status(500).json({ error: "Error, server connection refused" })

参考示例,

因此,将上面的代码段更改为,

/* 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);
    }

})

推荐阅读