Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
962 views
in Technique[技术] by (71.8m points)

javascript - axios interceptors response undefined

I'm trying to logout my user once they get a 401. I'm using axios to return data from the api

I was looking around and found the same axios.interceptors.response

  axios.interceptors.response.use(
    response => response,
  error => {
    const {status} = error.response;
    if (status === 401 ) {
      store.dispatch('snackBar', snackbarObj)
    } 
   return Promise.reject(error);
  }
)

It appears my error.response is undefined. I'm not sure what is wrong? any ideas?

console.dir of the error

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're not getting a response from the request you're doing with Axios since the browser received a 401 unauthorized response when doing the preflight OPTION request, resulting in a Network Error for the request you're trying to do.

This is related to how CORS works and how your backend handles OPTION requests. To understand how the backend server should handle preflight requests, it's important to understand what is the motivation behind introducing preflight requests.

The backend server should not check for authentication on OPTION requests, it should validate that the request is being made to an endpoint that accepts cross-domain requests and return a success code if it does.

Then, automatically, the browser will proceed with the initially intended request.

That way, the Axios interceptor will receive the 401 error code if the user is no longer authenticated.


Shameless self-promotion, I've published a simple Axios plugin called axios-middleware which helps abstract the use of Axios interceptors in bigger apps. It offers an example of middleware that automatically handles unauthenticated requests by trying to authenticate again before resending the request.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...