[英]JS Axios - how to get response body in event of error?
I want to be able to get the response body back from an Axios error catch.我希望能够从 Axios 错误捕获中获取响应正文。
I am using axios v0.18.0.我正在使用 axios v0.18.0。
My axios code looks like this:我的 axios 代码如下所示:
let service = axios.create({
baseURL: "https://baseUrl.azurewebsites.net",
responseType: "json"
});
service.defaults.headers.common['authorization'] = `Bearer ${token}`;
service.post("/api/method", params).then(result => {
console.log('success',result);
}).catch(error=>{
console.log('error');
console.log(error);
});
My API call is returning a 400 error as I expected, given my inputs.根据我的输入,我的 API 调用返回 400 错误,正如我所料。 So I am hitting the catch block.
所以我击中了catch块。 However I'm not able to retrieve the error message that's returned by the API call.
但是,我无法检索 API 调用返回的错误消息。
I've tried doing a console.out(error.response.data), but this returns null.我试过做一个console.out(error.response.data),但这返回null。
I've verified using Postman that the API call does return an error message in the response body, so the API isn't the problem.我已经使用 Postman 验证了 API 调用确实在响应正文中返回了一条错误消息,因此 API 不是问题所在。
What am I missing?我错过了什么?
I tested it with Mocky and the error message is indeed returned in error.response.data
.我用Mocky对其进行了测试,错误消息确实在
error.response.data
返回。
const axios = require('axios');
// http://www.mocky.io/v2/5c06f6be3000009600d25953 (the mock api to call, it always returns 400 with an error message)
let service = axios.create({
baseURL: "http://www.mocky.io",
responseType: "json"
});
service.post("/v2/5c06f6be3000009600d25953").then(result => {
console.log('success', result);
}).catch(error => {
console.log(error.response.data);
});
The code above prints Ooops, bad request!
上面的代码打印了
Ooops, bad request!
, as returned. ,作为返回。
EDIT: apparently the problem you described can happen for a variety of reasons.编辑:显然您描述的问题可能由于多种原因而发生。 See this issue.
看到这个问题。
Here is what I did to fix the problem.这是我为解决问题所做的工作。
let options = {
baseURL: "http://www.mocky.io",
responseType: "application/json"
};
//service.post("/v2/5c06f6be3000009600d25953",{}).then(result => {
axios.post("/v2/5c06f6be3000009600d25953",null,options).then(result => {
console.log('success', result);
}).catch(error => {
console.log(error.response);
});
The main modification was to change "responseType" to " application/json ".主要修改是将“responseType”更改为“ application/json ”。
Thanks for your help everyone.谢谢大家的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.