Axios拦截器,用于刷新令牌

时间:2020-10-22 07:29:00

标签: javascript reactjs redux axios thunk

我正在创建一个react + Django应用程序,并给了我一个访问令牌和一个刷新令牌。访问令牌将在5分钟后过期,并在24小时内刷新令牌。 Axios拦截器会检查状态是否为401(未授权),并尝试刷新它。现在的问题是,在我的redux-thunk动作中,我必须检查所有动作调用中“ refresh token”何时过期的情况。

这是我的axios拦截器代码

import { url } from "./constants";

const axios = require("axios");
const axiosApiInstance = axios.create();

const refreshAccessToken = async () => {
  const token = localStorage.getItem("refreshToken");

  const res = await axios.post(
    `${url}/accounts/token/refresh/`, { refresh: token }
  );

  return res.data.access;
}

// Request interceptor for API calls
axiosApiInstance.interceptors.request.use(
  async (config) => {
    const token = localStorage.getItem("accessToken")
    config.headers = {
      Authorization: `Bearer ${token}`,
      Accept: "application/json",
      //check this if causes problems
      "Content-Type": "application/json",
    };
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

// Response interceptor for API calls
axiosApiInstance.interceptors.response.use(
  (response) => {
    return response;
  },
  async function (error) {
    const originalRequest = error.config;
    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      const access_token = await refreshAccessToken();
      localStorage.setItem("accessToken", access_token);
      axios.defaults.headers.common["Authorization"] = "Bearer " + access_token;
      return axiosApiInstance(originalRequest);
    }
    return Promise.reject(error);
  }
);

export default axiosApiInstance;

如果刷新令牌已过期,我将无法进行api调用。但就我而言,如果刷新令牌也已过期,我希望能够调用redux操作注销。我在所有行动电话中都这样做

export const createVTP = (formProps, callback, id, template_type) => async (dispatch) => {
  const params = new URLSearchParams([
    ["template_type", template_type],
  ]);
  try {
    const res = await axiosApiInstance.post(
      `${url}/brokerage/${id}/trading/`,
      formProps,
      { params }
    );

    dispatch({
      type: CREATE_VTP_NONE,
      payload: res.data,
    });
    callback();
  } catch (err) {
    if (err?.response?.status === 401) {
      dispatch({
        type: AUTH_ERROR,
        payload: `Session expired. Please Sign in again`,
      });
    }
  }
};

是否有更好的方法来实现这一目标?很多重复的代码

0 个答案:

没有答案