简体   繁体   English

ReactJS Axios 拦截器响应/请求

[英]ReactJS Axios Interceptor Response/Request

I have a problem on using the axios interceptor in my react app.我在我的反应应用程序中使用 axios 拦截器时遇到问题。 I want to achieve putting the header token just once in my react app.我想在我的反应应用程序中只放置一次 header 令牌。 So thats why Im putting it in the interceptor.所以这就是为什么我把它放在拦截器中。 At the same time, i also want to have just one declaration to get the error.同时,我也希望只有一个声明来获取错误。 So i dont need to show the error in every page.所以我不需要在每一页都显示错误。 I'm wondering if i'm using it correctly in my code below?我想知道我是否在下面的代码中正确使用了它? Is there a way that i can shorten it cause i'm declaring it twice for response and request?有没有办法可以缩短它,因为我为响应和请求声明了两次?

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;
}

You don't need to set authorization header in interceptors.response, you only need this in request interceptor.您不需要在interceptors.response 中设置授权header,您只需要在请求拦截器中设置。

You could declare your error handling in a closure function (with the action dispatch) to avoid repeating yourself.您可以在闭包 function (使用动作调度)中声明您的错误处理以避免重复自己。

I would also suggest to avoid handling errors directly in axios instance.我还建议避免直接在 axios 实例中处理错误。 You could define async redux actions using https://github.com/reduxjs/redux-thunk , and handle network errors at redux level (using fetchBegin, fetchSuccess, fetchFailure actions pattern).您可以使用https://github.com/reduxjs/redux-thunk定义异步 redux 操作,并在 Z7490FE17CAEC373F2299D65B6E20E88CESS 级别处理网络错误, Then axios setup and redux setup would not be coupled anymore, which will allow you to change these tools in the future.然后 axios setup 和 redux setup 将不再耦合,这将允许您将来更改这些工具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM