【axios】拦截器:axios.interceptors.request.use|axios.interceptors.response.use

2024-06-04 1843阅读

文章目录

  • 概述
  • 设置拦截器
  • Axios 拦截器的实现
    • 任务注册
    • 任务编排
    • 任务调度
    • 来源

      概述

      axios有请求拦截器(request)、响应拦截器(response)、axios自定义回调处理(这里就是我们常用的地方,会将成功和失败的回调函数写在这里)

      执行顺序: 请求拦截器 -> api请求 -> 响应拦截器->自定义回调。 axios实现这个拦截器机制如下:

      【axios】拦截器:axios.interceptors.request.use|axios.interceptors.response.use 第1张

      假设我们定义了 请求拦截器1号(r1)、请求拦截器2号(r2)、响应拦截器1号(s1)、响应拦截器2号(s2)、自定义回调处理函数(my)

      那么执行结果是:r2 r1 s1 s2 my

      设置拦截器

      在 Axios 中设置拦截器很简单,通过 axios.interceptors.request 和 axios.interceptors.response 对象提供的 use 方法,就可以分别设置请求拦截器和响应拦截器:

      axios.interceptors.request.use(function (config) {
        config.headers.token = 'added by interceptor';
        return config;
      });
       
      // 添加响应拦截器 —— 处理响应对象
      axios.interceptors.response.use(function (data) {
        data.data = data.data + ' - modified by interceptor';
        return data;
      });
       
      axios({
        url: '/hello',
        method: 'get',
      }).then(res =>{
        console.log('axios res.data: ', res.data)
      })
      

      Axios 拦截器的实现

      任务注册

      要搞清楚任务是如何注册的,就需要了解 axios 和 axios.interceptors 对象。

      /**
       * Create an instance of Axios
       *
       * @param {Object} defaultConfig The default config for the instance
       * @return {Axios} A new instance of Axios
       */
      function createInstance(defaultConfig) {
        var context = new Axios(defaultConfig);
        var instance = bind(Axios.prototype.request, context);
       
        // Copy axios.prototype to instance
        utils.extend(instance, Axios.prototype, context);
       
        // Copy context to instance
        utils.extend(instance, context);
       
        return instance;
      }
       
      // Create the default instance to be exported
      var axios = createInstance(defaults);
       
      // Expose Axios class to allow class inheritance
      axios.Axios = Axios;
      

      bind函数:

      module.exports = function bind(fn, thisArg) {
        return function wrap() {
          var args = new Array(arguments.length);
          for (var i = 0; i  
      

      在 Axios 的源码中,我们找到了 axios 对象的定义,很明显默认的 axios 实例是通过 createInstance 方法创建的,该方法最终返回的是Axios.prototype.request 函数对象。同时,我们发现了 Axios的构造函数:

      /**
       * Create a new instance of Axios
       *
       * @param {Object} instanceConfig The default config for the instance
       */
      function Axios(instanceConfig) {
        this.defaults = instanceConfig;
        this.interceptors = {
          request: new InterceptorManager(),
          response: new InterceptorManager()
        };
      }
      

      在构造函数中,我们找到了 axios.interceptors 对象的定义,也知道了 interceptors.request 和 interceptors.response 对象都是 InterceptorManager 类的实例。因此接下来,进一步分析InterceptorManager 构造函数及相关的 use 方法就可以知道任务是如何注册的:

      function InterceptorManager() {
        this.handlers = [];
      }
       
      /**
       * Add a new interceptor to the stack
       *
       * @param {Function} fulfilled The function to handle `then` for a `Promise`
       * @param {Function} rejected The function to handle `reject` for a `Promise`
       *
       * @return {Number} An ID used to remove interceptor later
       */
      InterceptorManager.prototype.use = function use(fulfilled, rejected) {
        this.handlers.push({
          fulfilled: fulfilled,
          rejected: rejected
        });
        return this.handlers.length - 1;
      };
      

      通过观察 use 方法,我们可知注册的拦截器都会被保存到 InterceptorManager 对象的 handlers 属性中。下面我们用一张图来总结一下 Axios 对象与 InterceptorManager 对象的内部结构与关系:

      【axios】拦截器:axios.interceptors.request.use|axios.interceptors.response.use 第2张

      任务编排

      现在我们已经知道如何注册拦截器任务,但仅仅注册任务是不够,我们还需要对已注册的任务进行编排,这样才能确保任务的执行顺序。这里我们把完成一次完整的 HTTP 请求分为处理请求配置对象、发起 HTTP 请求和处理响应对象 3 个阶段。

      接下来我们来看一下 Axios 如何发请求的:

      axios({
        url: '/hello',
        method: 'get',
      }).then(res =>{
        console.log('axios res: ', res)
        console.log('axios res.data: ', res.data)
      })
      

      通过前面的分析,我们已经知道 axios 对象对应的是 Axios.prototype.request 函数对象,该函数的具体实现如下:

      Axios.prototype.request = function request(config) {
        /*eslint no-param-reassign:0*/
        // Allow for axios('example/url'[, config]) a la fetch API
        if (typeof config === 'string') {
          config = arguments[1] || {};
          config.url = arguments[0];
        } else {
          config = config || {};
        }
       
        config = mergeConfig(this.defaults, config);
       
        // Set config.method
        if (config.method) {
          config.method = config.method.toLowerCase();
        } else if (this.defaults.method) {
          config.method = this.defaults.method.toLowerCase();
        } else {
          config.method = 'get';
        }
       
        // Hook up interceptors middleware
        var chain = [dispatchRequest, undefined];
        var promise = Promise.resolve(config);
       
        this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
        //成对压入chain数组中,这里的成对是一个关键点,从代码处可以看出请求拦截器向chain中压入的时候使用的是unshift方法,也就是每次添加函数方法队都是从数组最前面添加,这也是为什么请求拦截器输出的时候是r2 r1。
          chain.unshift(interceptor.fulfilled, interceptor.rejected);
        });
       
        this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
        //与unshift不同的是,push函数一直被push到最尾部,那么形成的就是s1 s2的顺序,这也就解释响应拦截器函数是顺序执行的了。
          chain.push(interceptor.fulfilled, interceptor.rejected);
        });
       
        while (chain.length) {
          promise = promise.then(chain.shift(), chain.shift());
        }
       
        return promise;
      };
      

      任务编排的代码比较简单,我们来看一下任务编排前和任务编排后的对比图:

      【axios】拦截器:axios.interceptors.request.use|axios.interceptors.response.use 第3张

      任务调度

      任务编排完成后,要发起 HTTP 请求,我们还需要按编排后的顺序执行任务调度。在 Axios 中具体的调度方式很简单,具体如下所示:

        while (chain.length) {
          promise = promise.then(chain.shift(), chain.shift());
        }
       
        return promise;
      

      因为 chain 是数组,所以通过 while 语句我们就可以不断地取出设置的任务,然后组装成 Promise 调用链从而实现任务调度,对应的处理流程如下图所示:

      【axios】拦截器:axios.interceptors.request.use|axios.interceptors.response.use 第4张

      来源

      浅谈axios.interceptors拦截器

      axios 拦截器分析

      axios部分工作原理及常见重要问题的探析:


    免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

    目录[+]