【发布时间】: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