【问题标题】:ReactJS Axios Interceptor Response/RequestReactJS Axios 拦截器响应/请求
【发布时间】:2020-09-25 19:30:40
【问题描述】:

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

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】:

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

    您可以在闭包函数中声明您的错误处理(使用动作调度)以避免重复。

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

    【讨论】:

    • 谢谢。你能在闭包函数的错误处理上写一些代码吗?
    猜你喜欢
    • 2020-10-22
    • 2022-01-25
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    • 2022-11-14
    • 2018-10-03
    • 2020-11-21
    相关资源
    最近更新 更多