ReactJS Axios拦截器响应/请求

问题描述 投票:2回答:1

我在我的react应用程序中使用axios拦截器时遇到问题。我想实现将标头令牌仅放入我的react应用程序一次。这就是为什么我将其放入拦截器。同时,我也只想声明一个错误。所以我不需要在每个页面中显示错误。我想知道我是否在下面的代码中正确使用了它?有没有一种方法可以缩短它,因为我要两次声明它以进行响应和请求?

export function getAxiosInstance() {
  if (axiosInstance === null) {
    axiosInstance = axios.create({
      baseURL: API_URL,
    });
  }
  axiosInstance.interceptors.request.use(
    (config) => {
      if (config.baseURL === API_URL && !config.headers.Authorization) {
        const token = store.getState().auth.access_token;
        if (token) {
          config.headers.Authorization = `Bearer ${token}`;
          console.log(config);
        }
      }
      return config;
    },
    (error) => {
      console.log(error);
      store.dispatch(setAPIErrorMessage(error.message));
      return Promise.reject(error);
    }
  );
  axiosInstance.interceptors.response.use(
    (config) => {
      if (config.baseURL === API_URL && !config.headers.Authorization) {
        const token = store.getState().auth.access_token;
        if (token) {
          config.headers.Authorization = `Bearer ${token}`;
          console.log(config);
        }
      }
      return config;
    },
    (error) => {
      console.log(error);
      store.dispatch(setAPIErrorMessage(error.message));
      return Promise.reject(error);
    }
  );
  return axiosInstance;
}
javascript reactjs react-redux axios react-hooks
1个回答
1
投票

您不需要在interceptors.response中设置授权标头,只需在请求拦截器中就需要此。

您可以在闭包函数中声明错误处理(使用动作分派,以避免重复您自己。

我也建议避免直接在axios实例中处理错误。您可以使用https://github.com/reduxjs/redux-thunk定义异步redux操作,并在redux级别处理网络错误(使用fetchBegin,fetchSuccess,fetchFailure操作模式)。然后,axios设置和redux设置将不再耦合,这将使您将来可以更改这些工具。

© www.soinside.com 2019 - 2024. All rights reserved.