将拦截器添加到 axios 实例

Add Interceptors to instance of 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')]

有人知道如何实现吗?

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

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