Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error.response is undefined if axios request fails

Tags:

axios

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.

like image 623
Alexey Starinsky Avatar asked Nov 13 '18 15:11

Alexey Starinsky


2 Answers

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.

like image 107
Alexey Starinsky Avatar answered Oct 17 '22 15:10

Alexey Starinsky


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);
like image 5
Yue Dong Avatar answered Oct 17 '22 16:10

Yue Dong