我在后端使用node+express,并在前端做出反应。在节点中,我向客户端发送 400 错误响应:
return res.status(400).send("Invalid username!")
在 React 中,我通过 axios 调用这个 api:
await axios.post(url, user)
.then(res => {
if (res.status === 200) {
console.log("logged!")
}
else {
console.log(res)
}
})
当我故意为对象
user
输入错误的凭据时,它会给我 400 (Bad Request)
错误。但是,我无法收到 invalid username
消息。我查看网络面板(Chrome),在那里我可以看到该消息。我如何获得该消息回复?
我尝试过:
res.message
res.error
res.errors
res.body
没有任何作用。非常感谢!
但是
首先,您将
async/await
语法与 .then/.catch
混合在一起。它不是这样工作的,你需要做其中之一。
其次,这不是使用
.then/.catch
语法捕获错误的正确方法,您需要 .catch
方法来捕获这些错误。如果你想使用 async/await
,那么你需要使用 try/catch 块。
所以它需要像这样:
axios.post(url, user)
.then(res => {
console.log("logged!")
})
.catch(err => {
console.log(err);
})
或者像这样:
try {
const response = await axios.post(url, user);
console.log(response);
}
catch (err) {
console.log(err);
}
我遇到了同样的问题。
err.message
根据状态代码显示为通用消息,即使我使用 json
响应:
response.status(400).json({
message: "Invalid username!",
});
解决此问题的最佳方法是
console.log()
您的err
并找到自定义消息的隐藏位置。
正如我所期望的,Axios
图书馆似乎把它说得更深入一些。我的藏在err.response.data.message
如果您使用 Typescript,请使用以下代码以使其满意:
import axios, { AxiosError } from "axios";
......
try {
.....
}
catch (err) {
if (err instanceof AxiosError && !!err.response) {
throw new Error(err.response.data.message);
} else {
throw new Error("<Some other error message>");
}
}