在 express 中同时发送错误状态(res.status)和消息(res.json)

Sending error status(res.status) and message(res.json) both simultaneously in express

我正尝试根据从前端输入的表单在 express 中进行错误管理。我看到我可以发送 res.status(401) 作为错误代码或 res.json({}) 作为发送错误消息,但不能同时发送。我应该在下面做什么才能同时发送两者?

app.post('/verifyOTP', (req, res) => {
  const hash = req.body.hash;
  let [ hashValue, expires ] = hash.split('.');
  let now = Date.now();
    if (now > parseInt(expires)) {
        return res.status(400).json({ error: 'Timeout. Please try again' })
    }
})

您随时可以这样做

什么使 send 能够发送对象 :- 当参数是数组或对象时,Express 以 JSON 表示响应: 更多参考 express docs for send

我如何组合 .status and .send?:-设置响应的 HTTP 状态。它是 Node 的 response.statusCode. 的可链接别名以供更多参考 express status docs

app.post('/verifyOTP', (req, res) => {
  const hash = req.body.hash;
  let [ hashValue, expires ] = hash.split('.');
  let now = Date.now();
    if (now > parseInt(expires)) {
        return res.status(400).send({ error: 'Timeout. Please try again' })
    }
})

docs所述:

res.status(400).send({ error: 'Timeout. Please try again' })