前言

这应该是一个大多数都常用的请求库,因为它可以支持多种配置,跨平台实现,返回promise进行链式调用.完全过一遍源码可以提升自己对请求库的理解知识

什么是 axios?

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中

特性

  • 从浏览器中创建 XMLHttpRequests
  • 从 node.js 创建 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求数据和响应数据
  • 取消请求
  • 自动转换 JSON 数据
  • 客户端支持防御 XSRF

源码目录结构

├── /cancel/                 # 定义取消功能实现│ ├── Cancel.js                  # 请求被取消后抛出的对象,构造函数实现│ ├── isCancel.js                # 返回是否已经取消的布尔值│ └── CancelToken.js             # 用来请求取消操作的对象,构造函数实现├── /core/                   # 主要的核心功能实现│ ├── Axios.js                   # axios的构造函数│ ├── buildFullPath.js           # 返回基础地址和请求地址的合并URL│ ├── createError.js             # 创建指定错误对象的构造函数│ ├── dispatchRequest.js         # 使用配置的适配器发送请求到服务器│ ├── enhanceError.js            # 修改指定错误对象的信息│ ├── InterceptorManager.js      # 实现拦截器的构造函数│ ├── mergeConfig.js             # 合并配置│ ├── transformData.js           # 转换数据│ └── settle.js                  # 根据http响应状态,改变Promise的状态├── /helpers/                # 一些辅助方法│ ├── bind.js                    # bind实现方法│ ├── buildUR.js                 # URL末尾追加参数│ ├── combineURLs.js             # 合并URL│ ├── cookies.js                 # cookie操作│ ├── deprecatedMethod.js        # 警告已废弃请求方式│ ├── isAbsoluteURL.js           # 返回是否绝对路径的布尔值│ ├── isURLSameOrigin.js         # 返回是否同源的布尔值│ ├── normalizeHeaderName.js     # 标准化对比替换请求头│ ├── parseHeaders.js            # 将请求头解析成对象│ └── spread.js                  # 用于调用函数和展开参数数组的语法糖├── /adapters/               # 定义请求的适配器 xhr、http│ ├── http.js                    # nodejs默认适配器│ └── xhr.js                     # 浏览器默认适配器├── axios.js                 # 默认入口├── defaults.js              # 默认配置 └── utils.js                 # 工具函数

工具函数

这是axios的工具函数,我个人习惯是先看工具函数,因为这些一般会充斥到整个库,所以得先有个底知道有什么可以用的工具

axios/lib/utils.js

var bind = require('./helpers/bind');var isBuffer = require('is-buffer');/*global toString:true*/// utils is a library of generic helper functions non-specific to axiosvar toString = Object.prototype.toString;

引入了上面的bind函数和buffer检测库,和对象原型链上的toString方法,我们看看里面的bind是怎么样的

axios/lib/helpers/bind.js

module.exports = function bind(fn, thisArg) {  return function wrap() {      // 将参数数组化    var args = new Array(arguments.length);    for (var i = 0; i < args.length; i++) {      args[i] = arguments[i];    }    return fn.apply(thisArg, args);  };};

bind的简单实现,没疑问
源码地址

/** * Determine if a value is an Array * * @param {Object} val The value to test * @returns {boolean} True if value is an Array, otherwise false */function isArray(val) {  return toString.call(val) === '[object Array]';}/** * Determine if a value is an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is an ArrayBuffer, otherwise false */function isArrayBuffer(val) {  return toString.call(val) === '[object ArrayBuffer]';}/** * Determine if a value is a FormData * * @param {Object} val The value to test * @returns {boolean} True if value is an FormData, otherwise false */function isFormData(val) {  return (typeof FormData !== 'undefined') && (val instanceof FormData);}/** * Determine if a value is a view on an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false */function isArrayBufferView(val) {  var result;  if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {    result = ArrayBuffer.isView(val);  } else {    result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);  }  return result;}/** * Determine if a value is a String * * @param {Object} val The value to test * @returns {boolean} True if value is a String, otherwise false */function isString(val) {  return typeof val === 'string';}/** * Determine if a value is a Number * * @param {Object} val The value to test * @returns {boolean} True if value is a Number, otherwise false */function isNumber(val) {  return typeof val === 'number';}/** * Determine if a value is undefined * * @param {Object} val The value to test * @returns {boolean} True if the value is undefined, otherwise false */function isUndefined(val) {  return typeof val === 'undefined';}/** * Determine if a value is an Object * * @param {Object} val The value to test * @returns {boolean} True if value is an Object, otherwise false */function isObject(val) {  return val !== null && typeof val === 'object';}/** * Determine if a value is a Date * * @param {Object} val The value to test * @returns {boolean} True if value is a Date, otherwise false */function isDate(val) {  return toString.call(val) === '[object Date]';}/** * Determine if a value is a File * * @param {Object} val The value to test * @returns {boolean} True if value is a File, otherwise false */function isFile(val) {  return toString.call(val) === '[object File]';}/** * Determine if a value is a Blob * * @param {Object} val The value to test * @returns {boolean} True if value is a Blob, otherwise false */function isBlob(val) {  return toString.call(val) === '[object Blob]';}/** * Determine if a value is a Function * * @param {Object} val The value to test * @returns {boolean} True if value is a Function, otherwise false */function isFunction(val) {  return toString.call(val) === '[object Function]';}/** * Determine if a value is a Stream * * @param {Object} val The value to test * @returns {boolean} True if value is a Stream, otherwise false */function isStream(val) {  return isObject(val) && isFunction(val.pipe);}/** * Determine if a value is a URLSearchParams object * * @param {Object} val The value to test * @returns {boolean} True if value is a URLSearchParams object, otherwise false */function isURLSearchParams(val) {  return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;}/** * Trim excess whitespace off the beginning and end of a string * * @param {String} str The String to trim * @returns {String} The String freed of excess whitespace */function trim(str) {  return str.replace(/^\s*/, '').replace(/\s*$/, '');}/** * Determine if we're running in a standard browser environment * * This allows axios to run in a web worker, and react-native. * Both environments support XMLHttpRequest, but not fully standard globals. * * web workers: *  typeof window -> undefined *  typeof document -> undefined * * react-native: *  navigator.product -> 'ReactNative' * nativescript *  navigator.product -> 'NativeScript' or 'NS' */function isStandardBrowserEnv() {  if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||                                           navigator.product === 'NativeScript' ||                                           navigator.product === 'NS')) {    return false;  }  return (    typeof window !== 'undefined' &&    typeof document !== 'undefined'  );}

都是些利用基础语法的特性检测是否对应的数据类型

/** * Iterate over an Array or an Object invoking a function for each item. * * If `obj` is an Array callback will be called passing * the value, index, and complete array for each item. * * If 'obj' is an Object callback will be called passing * the value, key, and complete object for each property. * * @param {Object|Array} obj The object to iterate * @param {Function} fn The callback to invoke for each item */function forEach(obj, fn) {  // Don't bother if no value provided  if (obj === null || typeof obj === 'undefined') {    return;  }  // Force an array if not already something iterable  if (typeof obj !== 'object') {    /*eslint no-param-reassign:0*/    obj = [obj];  }  if (isArray(obj)) {    // Iterate over array values    for (var i = 0, l = obj.length; i < l; i++) {      fn.call(null, obj[i], i, obj);    }  } else {    // Iterate over object keys    for (var key in obj) {      if (Object.prototype.hasOwnProperty.call(obj, key)) {        fn.call(null, obj[key], key, obj);      }    }  }}

校验参数类型分别根据可迭代对象或数组做遍历,传递每个参数到指定方法执行,如果参数是对象只会遍历实例本身的属性.

/** * Accepts varargs expecting each argument to be an object, then * immutably merges the properties of each object and returns result. * * When multiple objects contain the same key the later object in * the arguments list will take precedence. * * Example: * * ```js * var result = merge({foo: 123}, {foo: 456}); * console.log(result.foo); // outputs 456 * ``` * * @param {Object} obj1 Object to merge * @returns {Object} Result of all merge properties */function merge(/* obj1, obj2, obj3, ... */) {  var result = {};  function assignValue(val, key) {    if (typeof result[key] === 'object' && typeof val === 'object') {      result[key] = merge(result[key], val);    } else {      result[key] = val;    }  }  // 将result和当前值做比较  for (var i = 0, l = arguments.length; i < l; i++) {    forEach(arguments[i], assignValue);  }  return result;}

接收多个参数对象,合并所有对象并返回结果,当多个对象包含相同的key时,后者会覆盖前者.其中的

forEach(arguments[i], assignValue);--------------等价于-------------------for (var key in arguments[i]) {  if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {    assignValue.call(null, arguments[i][key], key, arguments[i]);  }}--------------等价于-------------------for (var key in arguments[i]) {  if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {    if (typeof result[key] === 'object' && typeof arguments[i][key] === 'object') {      result[key] = merge(result[key], arguments[i][key]);    } else {      result[key] = val;    }  }}

利用递归合并每层对象

/** * Function equal to merge with the difference being that no reference * to original objects is kept. * * @see merge * @param {Object} obj1 Object to merge * @returns {Object} Result of all merge properties */function deepMerge(/* obj1, obj2, obj3, ... */) {  var result = {};  function assignValue(val, key) {    if (typeof result[key] === 'object' && typeof val === 'object') {      result[key] = deepMerge(result[key], val);    } else if (typeof val === 'object') {      result[key] = deepMerge({}, val);    } else {      result[key] = val;    }  }  for (var i = 0, l = arguments.length; i < l; i++) {    forEach(arguments[i], assignValue);  }  return result;}

merge相比,它只有在typeof result[key] === 'object' && typeof val === 'object'的时候才会进行合并否则直接赋值,而deepMerge只要assignValue的入参为对象则一定合并.

/** * Extends object a by mutably adding to it the properties of object b. * * @param {Object} a The object to be extended * @param {Object} b The object to copy properties from * @param {Object} thisArg The object to bind function to * @return {Object} The resulting value of object a */function extend(a, b, thisArg) {  forEach(b, function assignValue(val, key) {    if (thisArg && typeof val === 'function') {      a[key] = bind(val, thisArg);    } else {      a[key] = val;    }  });  return a;}

向某个对象添加另一个对象的属性的扩展函数,并且指定其中function绑定指向

module.exports = {  isArray: isArray,  isArrayBuffer: isArrayBuffer,  isBuffer: isBuffer,  isFormData: isFormData,  isArrayBufferView: isArrayBufferView,  isString: isString,  isNumber: isNumber,  isObject: isObject,  isUndefined: isUndefined,  isDate: isDate,  isFile: isFile,  isBlob: isBlob,  isFunction: isFunction,  isStream: isStream,  isURLSearchParams: isURLSearchParams,  isStandardBrowserEnv: isStandardBrowserEnv,  forEach: forEach,  merge: merge,  deepMerge: deepMerge,  extend: extend,  trim: trim};

以上为当前源码导出的所有工具函数

源码地址