用于令牌刷新的Axios全局拦截器

时间:2019-11-07 15:33:59

标签: javascript reactjs axios

好,所以这是我遇到的第三个问题,首先是我的axios配置文件

import axios from "axios";
import { withRouter } from "react-router-dom";

const instance = axios.create({
  baseURL: process.env.REACT_APP_API,
  headers: {
    "content-type": "application/json"
  },
  responseType: "json"
});
function pushToLogin() {
  this.props.history.push("/");
}
function createAxiosResponseInterceptor(axiosInstance) {
  const interceptor = axiosInstance.interceptors.response.use(
    response => response,
    error => {
      // Reject promise if usual error
      console.log(error);
      if (error.response.status !== 401) {
        return Promise.reject(error);
      }
      /*
       * When response code is 401, try to refresh the token.
       * Eject the interceptor so it doesn't loop in case
       * token refresh causes the 401 response
       */
      axiosInstance.interceptors.response.eject(interceptor);
      return axiosInstance
        .post("token/refresh/", {
          refresh: localStorage.getItem("refreshToken")
        })
        .then(response => {
          localStorage.setItem("accessToken", response.data.access);
          error.response.config.headers["Authorization"] =
            "Bearer " + response.data.access;
          return axiosInstance(error.response.config);
        })
        .catch(error => {
          localStorage.setItem("accessToken", null);
          localStorage.setItem("refreshToken", null);
          pushToLogin();
          return Promise.reject(error);
        })
        .finally(createAxiosResponseInterceptor(this));
    }
  );
}

createAxiosResponseInterceptor(instance);

export default withRouter(instance);

我想要的是: 请求获取401>获取新令牌并将其存储>重复请求>如果可以,我们很好,如果没有返回,这是正常错误。

发生了什么:请求获取401>获取新令牌并存储它>重复请求>如果好的话,我们很好,如果没有,它将进入拦截器的最后一个catch块,我认为这是专门针对的对于refreshToken请求,或者至少是我想要的。

奖金问题:如您所见,我想推送刷新令牌失败的登录信息,我正尝试为此使用withRouter,但我在该推送行上cannot read props of undefined,所以这是另一个问题。

非常感谢!

编辑:即使此请求是通过其他方式完成的,我也想知道我的代码出了什么问题而不是学习别人的代码。

1 个答案:

答案 0 :(得分:0)

我切换为使用axios-auth-refresh软件包,我正在使用的配置代码在这里:

import axios from "axios";
import createAuthRefreshInterceptor from "axios-auth-refresh";

const instance = axios.create({
  baseURL: process.env.REACT_APP_API,
  headers: {
    "content-type": "application/json"
  },
  responseType: "json"
});
const refreshAuthLogic = failedRequest =>
  instance
    .post("token/refresh/", {
      refresh: localStorage.getItem("refreshToken")
    })
    .then(tokenRefreshResponse => {
      localStorage.setItem("accessToken", tokenRefreshResponse.data.access);
      failedRequest.response.config.headers["Authorization"] =
        "Bearer " + tokenRefreshResponse.data.access;
      return Promise.resolve();
    })
    .catch(error => {
      console.log("refresh fail");
      localStorage.setItem("accessToken", null);
      localStorage.setItem("refreshToken", null);
      //pushToLogin();
      return Promise.reject(error);
    });
createAuthRefreshInterceptor(instance, refreshAuthLogic);

export default instance;