How to Get the Status Code from an Http Error in Axios

How can I get the status code from an HTTP error in Axios?

What you see is the string returned by the toString method of the error object. (error is not a string.)

If a response has been received from the server, the error object will contain the response property:

axios.get('/foo')
.catch(function (error) {
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
}
});

How to get statusCode from Axios?

It's very easy to get it:

axios
.get(url)
.then((response) => {
console.log(response.status);
})
.catch((error) => {
console.error({ error });
});

How can axios get the status code in .catch()?

I find in the interceptors configuration:

Axios.interceptors.response.use(
res => {

return res;
},
error => {

return Promise.reject(error.response.data)
}
);

I was return the error.response.data directly, I could configure it to error.response, or error.

if I configure the error.response, then in the .catch() I can console like bellow:

console.log(response.data);
console.log(response.status);
console.log(response.headers);

Accessing the HTTP error body data in an axios catch clause

You need to access the response object within error.

function (ent) {
return axios
.post(config.ROOT_API + '/api/backstory/', {new_parent_entity: ent, child_entity: this.entity})
.then(({data}) => {
console.log(data)
})
.catch((e) => {
console.log(e.response) // this returns
})

How to detect HTTP status code for every axios request?

try {
await axios.get(..)
} catch (error) {
// response is in error.response
}

Vue.js & Django - axios post response status 200 but called catch error

So the Axios call goes well, but after that, in the .then block an error is thrown and caught by the .catch block. This is also why the err.response is empty, because that is an error object of Axios. If you log the err instead of err.response you might see the actual error (as Akzhol Kadylbek suggested in his comment).

Looking at your code, I presume that error comes from this line:

this.this.me = res.data;
/// change to this.me = res.data;

The double this. looks like a typo.

Hope this helps.



Related Topics



Leave a reply



Submit