简体   繁体   English

Axios:对多个 axios 实例使用相同的拦截器

[英]Axios: use same interceptor with multiple axios instances

In my code base there are various Axios instances created using在我的代码库中,有各种 Axios 实例使用创建

axios.create()

because there are multiple base URLs used in my app.因为我的应用程序中使用了多个基本 URL。 So per baseURL we have created a corresponding Axios instance.因此,根据 baseURL,我们创建了一个相应的 Axios 实例。

Now in App.js file, I have included 2 interceptors现在在 App.js 文件中,我包含了 2 个拦截器

  1. request interceptor请求拦截器
  2. response interceptor响应拦截器
axios.interceptors.response.use(
        config => {
          return config;
        },
        error => {          
          if (error && error.response.status === 401) {
              signOut();
          }
          return Promise.reject(error);
        }
      );

But all the API calls are by-passing the above-mentioned 2 interceptors.但是所有 API 调用都绕过了上述 2 个拦截器。

Problem:问题:

I want to use the above-mentioned interceptors as the Global interceptors for all the Axios instances in my project.我想将上述拦截器用作我项目中所有 Axios 实例的全局拦截器。

First Option - "Easier"第一个选项 - “更容易”

Just create your own "axios generator" function.只需创建您自己的“axios 生成器”function。

const createAxios = (baseURL) => {
   const newInstance = axios.create({ baseURL });

   newInstance.interceptors.response.use(
      (config) => config,
      (error) => {
        if (error && error.response.status === 401) {
          signOut();
        }
        return Promise.reject(error);
      }
    );

    return newInstance;
}

Second Option - More Complicated Personally I prefer this option, as I find it more tidy, and logically separated and divided (each "entity" stands by itself).第二个选项 - 更复杂我个人更喜欢这个选项,因为我发现它更整洁,并且在逻辑上分开和划分(每个“实体”独立存在)。

What i would probably do is create a BasicService Class which would look something like this:我可能会做的是创建一个 BasicService Class,它看起来像这样:

import axios from 'axios';

class BasicService {
  constructor(url) {
    const options = {
      baseURL: url,
      // any options that you would want for all axios requests,
      // like (proxy, etc...)
    };
    
    this.fetcher = axios.create(options);

    // Your default config
    this.fetcher.interceptors.response.use(
      (config) => {
        return config;
      },
      (error) => {
        if (error && error.response.status === 401) {
          signOut();
        }
        return Promise.reject(error);
      }
    );
  }
}

then for each axios instance i would like to create, i would also create a class with all fetches.然后对于我想创建的每个 axios 实例,我还将创建一个包含所有提取的 class。 like:喜欢:

const baseURL= '/users';

class UserService extends Service {
  // GET Requests
  async GetAll() {
    return (await this.fetcher.get('/all')).data;
  }

  // POST Requests
  async insertUser(userToInsert) {
    return await this.fetcher.post(...)
  }
}

const userService = new UserService(baseURL);

export default userService;

then in any file i would just import my wanted service and fetch it然后在任何文件中我都会导入我想要的服务并获取它

import UserService from "/services/UserService";
UserService.getAll().then(...);

This helps you keep the same config for all axios instances while keeping your code as generic and clean as possible这有助于您为所有 axios 实例保持相同的配置,同时保持您的代码尽可能通用和干净

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

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