我有一个在后端使用 NodeJS 的应用程序,特别是 Express 框架来提供 API 路由服务。我的客户端是用 ReactJS 编写的,用于axios发出 API 请求。
第一次使用axios包,我找不到如何从响应中访问错误消息。
我的 API 返回错误响应:
res.status(404).send({ error: 'Error Message' });
Run Code Online (Sandbox Code Playgroud)
在axios我有:
axios.post('/api/users', newUser)
.then((user) => {
console.log(`User created: ${JSON.stringify(user)}`);
}).catch((err) => {
console.log(`Error : ${JSON.stringify(err)}`);
});
Run Code Online (Sandbox Code Playgroud)
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": …Run Code Online (Sandbox Code Playgroud)