我有axios请求的saga try-catch。然而,catch(err(会像一样返回消息
Error: Request failed with status code 400
我想显示来自服务器的错误消息,该消息由res.state(400(.json(errors(发送。在开发人员控制台上->在网络上,我清楚地看到我的JSON文件已经返回。
如何访问catch(err(块内返回的JSON?
您可以使用catch
捕获axios中的错误(块或函数-取决于您是使用try/catch
还是Promise API(。您可以使用error.response
访问失败响应数据。
以下是useEffect
钩子从端点获取数据并处理错误的示例。
useEffect(() => {
axios
.get("https://your-domain/error")
.then((response) => console.log("Response", response.body))
.catch((error) =>
console.log(`HTTP Status Code: ${error.response.status}; data: ${JSON.stringify(error.response.data)}`)
);
}, []);
端点本身是简单的Express端点,定义如下:
app.get("/error", (req, res) => {
console.log("error");
res.status(404).json({ error: "Not found" });
});
它返回404状态代码和{error: "Not found"}
正文的响应。