# 拦截器中间件

axios构造器类,可以看见请求响应拦截器都是由InterceptorManager构造器生成。

this.interceptors = {
    request: new InterceptorManager(),
    response: new InterceptorManager()
};

因此,我们需要进入InterceptorManager构造器中,看看它做了哪些事情?

其文件路径为lib/core/InterceptorManager.js,源码如下:

var utils = require('./../utils');

// 拦截器构造函数
function InterceptorManager() {
  // 唯一实例属性,为数组类型(意思是可以存在多个拦截器)
  this.handlers = [];
}


// 订阅拦截器原型use方法
// 通过use来注册一个拦截器的fulfilled与rejected函数
// 结合axios构造器中的实例属性可以得知
// 使用方式: axios.interceptors.request.use 或 axios.interceptors.response.use
InterceptorManager.prototype.use = function use(fulfilled, rejected) {
  // 当前数组添加一个拦截器
  this.handlers.push({
    fulfilled: fulfilled,
    rejected: rejected
  });
  // 返回当前拦截器的索引
  return this.handlers.length - 1;
};

// 移除指定拦截器
InterceptorManager.prototype.eject = function eject(id) {
  if (this.handlers[id]) {
    this.handlers[id] = null;
  }
};

// 遍历拦截器,跳过被注销的拦截器(axios构造器类中使用了此方法)
// this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
//    ...
// });
InterceptorManager.prototype.forEach = function forEach(fn) {
  utils.forEach(this.handlers, function forEachHandler(h) {
    if (h !== null) {
      fn(h);
    }
  });
};

module.exports = InterceptorManager;

其做了如下功能:

  • 添加拦截器,返回索引
  • 根据索引,删除拦截器
  • 遍历拦截器

其核心逻辑就是维护一个数组对象,提供了对数组的操作

# 总结

拦截器代码很少,每个数组对象存放两个函数fulfilledrejected

最近更新时间: 2023/3/21 19:40:56