如何在 res.status(404) 之后将 json 数据从后端 (express.js) 发送到前端 (react)?

How to send json data from the backend (express.js) to the frontend (react) after res.status(404)?

我正在制作一个连接到快速服务器的 React 登录应用程序,一切正常,现在我正在尝试处理错误。 当用户发送用户名和密码时,我会快速检查用户是否存在于数据库中,如果不存在,则将状态设置为 404 并发送 json 我想在前端抓取的错误在警报中显示该错误。 问题是,即使在前端出现 404 错误,json 消息数组也不会出现。 这是我的代码:

router.post('/login', async (req, res) => {
  const { username, password } = req.body;

  // check if user exists
  const user = await User.findOne({ username });
  console.log('user: ', user);
  // if the user doesn't exst
  if (!user) {
    return res.status(404).json({
      erros: [
        {
          msg: 'No user found',
        },
      ],
    });
  }

这是我得到的错误:

知道为什么错误数组没有发送到前端吗?

请使用以下代码发送 json 对象以及状态码 404

res.status(404).send({
  erros: [
    {
      msg: 'No user found',
    },
  ],
});

假设你在前端使用axios,那将下降到.catch,所以它会像这样

axios.post(...).catch((error) => {
console.log(error.response.data) // <- that's your response data
});

您的代码有效,只是在前端捕获的方式错误