Axios Interceptor Response Token Refresh API called but getting Token is expired regardless in refreshToken API & lator all APIs

后端 未结 1 1549
悲&欢浪女
悲&欢浪女 2020-12-18 17:38

my axios interceptor is:-

axios.interceptors.response.use((response, error) => {
  const originalRequest = response.config;

  if (response.data.status ==         


        
相关标签:
1条回答
  • 2020-12-18 18:14

    Usually the flow should be as such:

    1. making a regular request with accessToken
    2. request fails with status code 401
    3. axios interceptor catches it and makes request to token/refresh. from that response it gets a new access token.
    4. retries the original request.

    So the code should looks like this (this is a working example from my app):

    function isUnAuthorizedError(error) {
      return error.config && error.response && error.response.status === 401;
    }
    
    function shouldRetry(config) {
      return config.retries.count < 3;
    }
    
    function updateAuthToken(response) {
      localStorage.setItem('token', response.data.accessToken);
    }
    
    async function authInterceptor(error) {
      error.config.retries = error.config.retries || {
        count: 0,
      };
    
      if (isUnAuthorizedError(error) && shouldRetry(error.config)) {
        const response = await axios.post(`/token/refresh`, {});
    
        updateAuthToken(response);
    
        error.config.retries.count += 1;
        axios.defaults.headers.common.Authorization = `Bearer ${response.data.accessToken}`; // update the accessToken
        return axios.rawRequest(error.config); // retries the original request
      }
      return Promise.reject(error);
    }
    
    axios.interceptors.response.use(null, authInterceptor); // This indicates that authInterceptor will work only on request errors (status code >= 400)
    

    Hopes this flow makes more sense.

    0 讨论(0)
提交回复
热议问题