8

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.

Alexey Starinsky
  • 2,503
  • 1
  • 8
  • 38

3 Answers3

3

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.

Alexey Starinsky
  • 2,503
  • 1
  • 8
  • 38
  • 4
    Is this addressing the question or your immediate problem that led you to this question? – Ash Aug 05 '20 at 01:16
0

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.

Simone
  • 17,439
  • 10
  • 67
  • 96
  • Did you mean adding 'error = JSON.parse(JSON.stringify(error))' into the second lambda? – Alexey Starinsky Nov 13 '18 at 15:35
  • Did you mean Vuex action? How does it relate to axios? – Alexey Starinsky Nov 13 '18 at 15:40
  • 1
    Check the discussion on GitHub, looks like either axios or vuex (or maybe both) are mangling the error response. The trick (as you pointed out as well) is to JSON.stringify and then JSON.parse the error. Just try that and you should be able to see the actual error response – Simone Nov 14 '18 at 09:57
  • I tried 'error = JSON.parse(JSON.stringify(error))' in the interceptor, but with no success. – Alexey Starinsky Nov 14 '18 at 11:10
  • 1
    I'm afraid I can't help much further as I'm not familiar with Vuex, but you might be able to find the solution on the GitHub discussion. They labeled it as a non-issue and closed it, but people are still commenting there. – Simone Nov 14 '18 at 11:35
0

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);
dippas
  • 49,171
  • 15
  • 93
  • 105