【问题标题】:Axios does not send appropriate error response [React]Axios 没有发送适当的错误响应 [React]
【发布时间】:2022-01-24 17:55:19
【问题描述】:

我正在尝试使用 React 处理来自 Axios 的错误响应,但是当我尝试通过控制台记录它时,错误是 Network error 并且 error.response 未定义。

请求是一个简单的 POST,正确设置了 Authorization 标头,当我尝试在 Postman 上执行相同的请求时,它可以正常工作,并且我能够看到错误响应。

在用户填写表单并单击按钮后发出请求。

async function create() {
  const response = await Axios.post(
    "/api/disposal-requests/", // the base url is setted when the application mounts `Axios.defaults.baseURL = process.env.REACT_APP_API_URL`
    {
      description: "Description",
      url: "Url",
      key: "Key",
      location_geoname_id: "City",
    }
  );

  return response.data;
}

当用户点击一个按钮时,会有另一个函数调用create

async function onClick() {
  try {
    await create();
    // Everything works fine when there are no errors
  } catch(error) {
    // Here error.response is undefined
  }
}

这是我在 console.log 中收到的,在 Network tab 我可以看到错误状态为 400,但即使没有错误响应,我也只能在 Postman 上看到错误响应。

有人知道这里出了什么问题吗?

【问题讨论】:

  • create() 是一个异步函数,你不需要等待它,
  • 我已经编辑了答案,因为我写了一个代码示例,我在真实代码中等待它

标签: javascript reactjs axios


【解决方案1】:

请在 creat() 之前写 await。这样如果发生任何错误,请使用 get 来捕获

async function onClick() {
    try {
      await create();
      // Everything works fine when there are no errors
    } catch (error) {
      // Here the error response is undefined
    }
  }

【讨论】:

  • 我已经编辑了答案,因为我写了一个代码示例,我在真实代码中等待它
  • 好的,成功了吗?
  • 不,我的意思是我已经在实际代码中等待函数,所以问题不在于那个
猜你喜欢
  • 2019-06-29
  • 1970-01-01
  • 2016-07-11
  • 2020-02-23
  • 2021-08-15
  • 1970-01-01
  • 1970-01-01
  • 2013-11-08
  • 1970-01-01
相关资源
最近更新 更多