【问题标题】:How to send json data from the backend (express.js) to the frontend (react) after res.status(404)?res.status(404)后如何将json数据从后端(express.js)发送到前端(react)?
【发布时间】:2026-01-24 07:05:01
【问题描述】:

我正在制作一个连接到快速服务器的反应登录应用程序,一切正常,现在我正在尝试处理错误。 当用户发送用户名和密码时,我会检查用户是否存在于数据库中,如果不存在,则将状态设置为 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',
        },
      ],
    });
  }

这是我得到的错误:

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

【问题讨论】:

    标签: reactjs express error-handling try-catch backend


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      假设你在前端使用axios,那会落到.catch,所以会是这样的

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

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

      【讨论】:

        最近更新 更多