Alexey Starinsky
Alexey Starinsky

Reputation: 4295

error.response is undefined if axios request fails

I cannot access the error (response) status code if an axios request has failed in my Vue.js app. I cannot figure out why the response is undefined in both '.catch' and 'axios.interceptors.response'. I followed this instruction that demonstrates that 'error.response' can be easily accessed with a code like this:

axios.interceptors.response.use(
  (response) => { 
    console.log(response);
    return response;
  },  
  (error) => {
    handleApiFail(error.response);
  });

If I add this code to 'main.js' in my app, 'handleApiFail' is called when a request fails, but error.response is undefined in the second lambda and the first lambda is not called. If a request succeeded the 'response' in the first lambda is defined and has the status code.

EDIT1: this is not an option because my OPTIONS requests do not require authorization. Also there are various posts describing the same situation.

Upvotes: 17

Views: 42186

Answers (5)

Hanna Kim
Hanna Kim

Reputation: 11

You should return return Promise.reject(error) in the error function.
If you're developing locally, you'll need to restart the server after the modification.

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });

Upvotes: 0

tan js
tan js

Reputation: 294

Here is the operation that may help on some conditions:

error = JSON.parse(JSON.stringify(error))

then try to read the error.propertyNames or error["propertyNames"]

Thanks

Upvotes: 5

Yue Dong
Yue Dong

Reputation: 71

I have code like this:

axios.interceptors.response.use(null, (error) => {
    .........
    return Promise.reject();
});

Then, I found I miss to return my "error" in promise reject, correct like this:

return Promise.reject(error);

Upvotes: 7

Alexey Starinsky
Alexey Starinsky

Reputation: 4295

The lack of

access-control-allow-origin: *

header in the response caused the browser to block my request.

Adding the header makes axios work fine.

Upvotes: 4

Simone
Simone

Reputation: 21262

This is an idiosyncrasy of axios. A quick solution to this is to serialize the response:

JSON.stringify(error)

Please refer to this GitHub issue for more info: https://github.com/axios/axios/issues/960

As someone pointed out there, you can check the error status code in the action and run some other commit depending on it.

Upvotes: 3

Related Questions