javascript - ReactJS Axios 拦截器响应/请求

标签 javascript reactjs react-redux axios react-hooks

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

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

最佳答案

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

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

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

关于javascript - ReactJS Axios 拦截器响应/请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62234869/

相关文章:

javascript - CORS 问题 - Angular/PHP/Apache

javascript - 在 jQuery 延迟对象中设置依赖关系的简写是什么?

javascript - 无法在现有状态转换期间更新 - 未使用任何非法的 setState()

reactjs - 异步重组 withHandlers ...?

javascript - react - Redux 应用程序 : "Invalid attempt to spread non-iterable instance" Issue

javascript - React.js Redux reducer 不插入项目

javascript - 语义 UI React Modal : Portal. render():必须返回有效的 React 元素(或 null)

javascript - 无法读取模板中未定义的属性

javascript - 如果父窗口关闭,如何关闭子窗口?

reactjs - 当我使用 react Hook 单击按钮时如何更改背景颜色