【问题标题】:Catching error messages from a NodeJS express application using axios使用 axios 从 NodeJS express 应用程序中捕获错误消息
【发布时间】:2020-07-15 21:20:27
【问题描述】:

我有一个在后端使用 NodeJS 的应用程序,特别是 Express 框架来提供 API 路由。我的客户端是用 ReactJS 编写的,利用axios 来发出 API 请求。

第一次使用axios 包,我找不到如何从响应中访问错误消息。

我的 API 作为错误响应返回:

res.status(404).send({ error: 'Error Message' });

axios 我有:

axios.post('/api/users', newUser)
  .then((user) => {
    console.log(`User created: ${JSON.stringify(user)}`);
  }).catch((err) => {
    console.log(`Error : ${JSON.stringify(err)}`);
  });

console.log(`Error : ${JSON.stringify(err)}`) 打印:

{
  "message": "Request failed with status code 404",
  "name": "Error",
  "stack": "Error: Request failed with status code 404\n    at createError (http://localhost:3000/static/js/0.chunk.js:13853:15)\n    at settle (http://localhost:3000/static/js/0.chunk.js:14074:12)\n    at XMLHttpRequest.handleLoad (http://localhost:3000/static/js/0.chunk.js:13328:7)",
  "config": {
    "url": "/api/users",
    "method": "post",
    "data": "someData",
    "headers": {
      "Accept": "application/json, text/plain, */*",
      "Authorization": "Bearer xxxxx",
      "Content-Type": "application/json;charset=utf-8"
    },
    "transformRequest": [
      null
    ],
    "transformResponse": [
      null
    ],
    "timeout": 0,
    "xsrfCookieName": "XSRF-TOKEN",
    "xsrfHeaderName": "X-XSRF-TOKEN",
    "maxContentLength": -1
  }
}

我在 err 对象中找不到来自服务器的响应消息,我什至尝试过:

res.status(404).json({ error: 'Error Message' });

没有成功。

【问题讨论】:

    标签: node.js reactjs express axios


    【解决方案1】:

    根据this comment,尝试访问catch 块中的err.response

    【讨论】:

    • 谢谢,可以在 err.response.data 中找到。所有 express js 作为响应发送的都位于数据对象中
    • 很高兴能帮上忙!
    【解决方案2】:

    err.response 将有一个对象{ error: 'Error Message' },因此您可以使用err.response.error 访问它。还要确保err.response.error 存在,因为如果它不存在并且您尝试访问它会在catch 中抛出一个错误,说err.response.error is undefined

    axios.post('/api/users', newUser)
      .then((user) => {
        console.log(`User created: ${JSON.stringify(user)}`);
      }).catch((err) => {
       if(err.response.error)
        console.log(`Error : ${JSON.stringify(err.response.error)}`);
      });
    

    【讨论】:

      猜你喜欢
      • 2019-07-26
      • 2018-10-13
      • 1970-01-01
      • 2018-05-15
      • 1970-01-01
      • 2018-03-25
      • 2020-08-17
      • 2018-07-06
      • 1970-01-01
      相关资源
      最近更新 更多