首页 > 解决方案 > 将拦截器添加到 axios 的实例

问题描述

我正在尝试使用 React Native 在 axios 拦截器上更新我的应用程序令牌。我有这段代码可以连接到 API 后端:

const requestHelper = axios.create({
  baseURL: "http://192.168.0.15:8000/api/",
  headers: {
    "Content-Type": "application/json",
    Authorization: "token 3260b30bdbc19a5c4deed87327536e443c751d27",
  },
});

const routes = {
  accounts: {
    getUser: () =>
      requestHelper({
        method: "get",
        url: "accounts/detail/",
      }),
.....

这是有效的,但令牌是硬编码的。现在,每次请求 API 调用时,我都需要从 AsyncStorage 更新该令牌。我试图使用 Axios 拦截器但不工作。这些是我的测试:

const requestHelper = axios.create({
  baseURL: "http://192.168.0.15:8000/api/",
  headers: {
    "Content-Type": "application/json",
  },
});

const createInterceptors = (instance) => {
  instance.interceptors.request.use(
    (config) => {
      config.headers = {
        Authorization: "token 3260b30bdbc19a5c4deed87327536e443c751d27",
      };
      return instance;
    },
    (error) => {
      return Promise.reject(error);
    }
  );
  return instance;
};

const routes = {
  accounts: {
    getUser: () =>
      createInterceptors(
        requestHelper({
          method: "get",
          url: "accounts/detail/",
        })
      ),
....

令牌在这里也是硬编码的,但用于测试目的。此测试引发错误:

[Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'instance.interceptors.request')]

有谁知道如何实施?

标签: reactjsreact-nativeaxiosinterceptorasyncstorage

解决方案


我解决了。我必须像这样添加拦截器功能:

const requestHelper = axios.create({
  baseURL: "http://192.168.0.15:8000/api/",
  headers: {
    "Content-Type": "application/json",
  },
});

requestHelper.interceptors.request.use(async (config) => {
  const token = await AsyncStorage.getItem("token");
  config.headers = {
    Authorization: "token " + token,
  };
  return config;
});

推荐阅读