如何正确设置带有 React Context 的 Axios 拦截器?

hak*_*man 19 javascript jwt reactjs axios jwt-auth

由于我想使用 React Context 设置 Axios 拦截器,因此似乎可行的唯一解决方案是创建一个拦截器组件,以便使用 useContext 挂钩来访问 Context 状态和分派。

问题是,这会创建一个闭包,并在调用拦截器时将旧数据返回给拦截器。

我正在使用 React/Node 使用 JWT 身份验证,并且我正在使用 Context API 存储访问令牌。

这就是我的拦截器组件现在的样子:

import React, { useEffect, useContext } from 'react';
import { Context } from '../../components/Store/Store';
import { useHistory } from 'react-router-dom';
import axios from 'axios';

const ax = axios.create();

const Interceptor = ({ children }) => {
  const [store, dispatch] = useContext(Context);

  const history = useHistory();

  const getRefreshToken = async () => {
    try {
      if (!store.user.token) {
        dispatch({
            type: 'setMain',
            loading: false,
            error: false,
            auth: store.main.auth,
            brand: store.main.brand,
            theme: store.main.theme,
          });

        const { data } = await axios.post('/api/auth/refresh_token', {
          headers: {
            credentials: 'include',
          },
        });

        if (data.user) {
          dispatch({
            type: 'setStore',
            loading: false,
            error: false,
            auth: store.main.auth,
            brand: store.main.brand,
            theme: store.main.theme,
            authenticated: true,
            token: data.accessToken,
            id: data.user.id,
            name: data.user.name,
            email: data.user.email,
            photo: data.user.photo,
            stripeId: data.user.stripeId,
            country: data.user.country,
            messages: {
              items: [],
              count: data.user.messages,
            },
            notifications:
              store.user.notifications.items.length !== data.user.notifications
                ? {
                    ...store.user.notifications,
                    items: [],
                    count: data.user.notifications,
                    hasMore: true,
                    cursor: 0,
                    ceiling: 10,
                  }
                : {
                    ...store.user.notifications,
                    count: data.user.notifications,
                  },
            saved: data.user.saved.reduce(function (object, item) {
              object[item] = true;
              return object;
            }, {}),
            cart: {
              items: data.user.cart.reduce(function (object, item) {
                object[item.artwork] = true;
                return object;
              }, {}),
              count: Object.keys(data.user.cart).length,
            },
          });
        } else {
          dispatch({
            type: 'setMain',
            loading: false,
            error: false,
            auth: store.main.auth,
            brand: store.main.brand,
            theme: store.main.theme,
          });
        }
      }
    } catch (err) {
      dispatch({
        type: 'setMain',
        loading: false,
        error: true,
        auth: store.main.auth,
        brand: store.main.brand,
        theme: store.main.theme,
      });
    }
  };

  const interceptTraffic = () => {
     ax.interceptors.request.use(
        (request) => {
            request.headers.Authorization = store.user.token
              ? `Bearer ${store.user.token}`
              : '';

            return request;
          },
        (error) => {
          return Promise.reject(error);
        }
      );

      ax.interceptors.response.use(
        (response) => {
          return response;
        },
        async (error) => {
          console.log(error);
          if (error.response.status !== 401) {
            return new Promise((resolve, reject) => {
              reject(error);
            });
          }

          if (
            error.config.url === '/api/auth/refresh_token' ||
            error.response.message === 'Forbidden'
          ) {
            const { data } = await ax.post('/api/auth/logout', {
              headers: {
                credentials: 'include',
              },
            });
            dispatch({
              type: 'resetUser',
            });
            history.push('/login');

            return new Promise((resolve, reject) => {
              reject(error);
            });
          }

          const { data } = await axios.post(`/api/auth/refresh_token`, {
            headers: {
              credentials: 'include',
            },
          });

          dispatch({
            type: 'updateUser',
            token: data.accessToken,
            email: data.user.email,
            photo: data.user.photo,
            stripeId: data.user.stripeId,
            country: data.user.country,
            messages: { items: [], count: data.user.messages },
            notifications:
              store.user.notifications.items.length !== data.user.notifications
                ? {
                    ...store.user.notifications,
                    items: [],
                    count: data.user.notifications,
                    hasMore: true,
                    cursor: 0,
                    ceiling: 10,
                  }
                : {
                    ...store.user.notifications,
                    count: data.user.notifications,
                  },
            saved: data.user.saved,
            cart: { items: {}, count: data.user.cart },
          });

          const config = error.config;
          config.headers['Authorization'] = `Bearer ${data.accessToken}`;

          return new Promise((resolve, reject) => {
            axios
              .request(config)
              .then((response) => {
                resolve(response);
              })
              .catch((error) => {
                reject(error);
              });
          });
        }
      );
  };

  useEffect(() => {
    getRefreshToken();
    if (!store.main.loading) interceptTraffic();
  }, []);

  return store.main.loading ? 'Loading...' : children;
}

export { ax };
export default Interceptor;
Run Code Online (Sandbox Code Playgroud)

getRefreshToken如果 cookie 中有刷新令牌,则每次用户刷新网站时都会调用该函数以检索访问令牌。

interceptTraffic功能是问题仍然存在的地方。它由一个请求拦截器组成,它将带有访问令牌的标头附加到每个请求和一个响应拦截器,用于处理访问令牌到期以便使用刷新令牌获取新的。

您会注意到我正在导出axAxios我添加拦截器的一个实例),但是当它在此组件外被调用时,由于关闭,它引用了旧的存储数据。

这显然不是一个好的解决方案,但这就是为什么我需要帮助组织拦截器同时仍然能够访问上下文数据。

请注意,我将此组件创建为包装器,因为它呈现提供给它的子组件,这是主要的 App 组件。

任何帮助表示赞赏,谢谢。

Has*_*war 5

通用方法(localStorage)

将 JWT 存储在 localStorage 中是一种常见的做法

localStorage.setItem('token', 'your_jwt_eykdfjkdf...');
Run Code Online (Sandbox Code Playgroud)

在登录或页面刷新时,创建一个模块,导出带有附加令牌的 Axios 实例。我们将从 localStorage 获取令牌

自定义 axios.js

import axios from 'axios';

// axios instance for making requests 
const axiosInstance = axios.create();

// request interceptor for adding token
axiosInstance.interceptors.request.use((config) => {
  // add token to request headers
  config.headers['Authorization'] = localStorage.getItem('token');
  return config;
});

export default axiosInstance;

Run Code Online (Sandbox Code Playgroud)

然后,只需导入我们刚刚创建的 Axios 实例并发出请求。

import axios from './custom-axios';

axios.get('/url');
axios.post('/url', { message: 'hello' });
Run Code Online (Sandbox Code Playgroud)

另一种方法(当您将令牌存储在状态中时)

如果您将 JWT 存储在 state 中,或者您可以从 state 中获取新令牌,请创建一个模块,该模块导出一个函数,该函数将令牌作为参数并返回一个带有附加令牌的 axios 实例,如下所示:

自定义 axios.js

import axios from 'axios';

const customAxios = (token) => {
  // axios instance for making requests
  const axiosInstance = axios.create();

  // request interceptor for adding token
  axiosInstance.interceptors.request.use((config) => {
    // add token to request headers
    config.headers['Authorization'] = token;
    return config;
  });

  return axiosInstance;
};

export default customAxios;

Run Code Online (Sandbox Code Playgroud)

然后导入我们刚刚创建的函数,从状态中获取令牌,并发出请求:

import axios from './custom-axios';

// logic to get token from state (it may vary from your approach but the idea is same)
const token = useSelector(token => token);

axios(token).get('/url');
axios(token).post('/url', { message: 'hello' });
Run Code Online (Sandbox Code Playgroud)