axios二次封装

188 阅读9分钟

在前端的开发的大多数界面中需要调用的接口都不止一个,如果不进行封装,那么我们的组件中可能会出现数十上百行请求接口重复的代码,随着请求的体量越来越大,我们的项目便越来越难以维护。

axios.post(`/api/xxxx/xxxx?xxx=${xxx}`, { ...data })
.then((result) => {
    if (result.errno) {
        ....
    } else {
        ....
    }
})
.catch((err) => {
    ....
})

进行axios二次封装,可以使代码进行统一管理,更具可读性,便于维护。

一,axios相关配置

Axios 是一个基于 promise 网络请求库,作用于node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js 的http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。
地址:www.axios-http.cn/

1 axios的特性

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

2 axios的API

  • axios.request(config):axios原型上的方法,是axios项目的核心处理方法,实现用户自定义配置、应用拦截器、发送请求核心功能
 // 支持axios(url, config)
if (typeof config === 'string') {
    config = utils.merge({
      url: arguments[0]
    }, arguments[1]);
  }
// 应用自定义配置
  config = utils.merge(defaults, {method: 'get'}, this.defaults, config);

  config.method = config.method.toLowerCase();
  • axios.get(url[, config]):用于获取数据, 请求指定的信息,返回实体对象
  • axios.delete(url[, config]):用于删除数据。
  • axios.head(url[, config]): 获取报文首部
  • axios.post(url[, data[, config]]):用于提交数据(新建)、包括表单提交及文件上传。
  • axios.put(url[, data[, config]]):用于更新数据(修改),将所有数据都推送到后端。
  • axios.patch(url[, data[, config]]):用于更新数据(修改),只将修改的数据推送到后端
  • axios.create(config):创建axios实例

3 请求的配置

这些是创建请求时可以用的配置选项。只有 url 是必需的。如果没有指定 method,请求将默认使用 GET 方法。

{
  // `url` 是用于请求的服务器 URL
  url: '/user',
  // `method` 是创建请求时使用的方法
  method: 'get', // 默认值
  // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
  // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
  baseURL: 'https://some-domain.com/api/',
  // `transformRequest` 允许在向服务器发送前,修改请求数据
  // 它只能用于 'PUT', 'POST' 和 'PATCH' 这几个请求方法
  // 数组中最后一个函数必须返回一个字符串, 一个Buffer实例,ArrayBuffer,FormData,或 Stream
  // 你可以修改请求头。
  transformRequest: [function (data, headers) {
    // 对发送的 data 进行任意转换处理
    return data;
  }],
  // `transformResponse` 在传递给 then/catch 前,允许修改响应数据
  transformResponse: [function (data) {
    // 对接收的 data 进行任意转换处理
    return data;
  }],

  // 自定义请求头
  headers: {'X-Requested-With': 'XMLHttpRequest'},
  
  // `params` 是与请求一起发送的 URL 参数,拼接的url参数
  // 必须是一个简单对象或 URLSearchParams 对象
  params: {
    ID: 12345
  },
  // `paramsSerializer`是可选方法,主要用于序列化`params`
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function (params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

  // `data` 是作为请求体被发送的数据
  // 仅适用 'PUT', 'POST', 'DELETE 和 'PATCH' 请求方法
  // 在没有设置 `transformRequest` 时,则必须是以下类型之一:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - 浏览器专属: FormData, File, Blob
  // - Node 专属: Stream, Buffer
  data: {
    firstName: 'Fred'
  },
  
  // 发送请求体数据的可选语法
  // 请求方式 post
  // 只有 value 会被发送,key 则不会
  data: 'Country=Brasil&City=Belo Horizonte',

  // `timeout` 指定请求超时的毫秒数。
  // 如果请求时间超过 `timeout` 的值,则请求会被中断
  timeout: 1000, // 默认值是 `0` (永不超时)

  // `withCredentials` 表示跨域请求时是否需要使用凭证
  withCredentials: false, // default

  // `adapter` 允许自定义处理请求,这使测试更加容易。
  // 返回一个 promise 并提供一个有效的响应 (参见 lib/adapters/README.md)。
  adapter: function (config) {
    /* ... */
  },

  // `auth` HTTP Basic Auth
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

  // `responseType` 表示浏览器将要响应的数据类型
  // 选项包括: 'arraybuffer', 'document', 'json', 'text', 'stream'
  // 浏览器专属:'blob'
  responseType: 'json', // 默认值

  // `responseEncoding` 表示用于解码响应的编码 (Node.js 专属)
  // 注意:忽略 `responseType` 的值为 'stream',或者是客户端请求
  // Note: Ignored for `responseType` of 'stream' or client-side requests
  responseEncoding: 'utf8', // 默认值

  // `xsrfCookieName` 是 xsrf token 的值,被用作 cookie 的名称
  xsrfCookieName: 'XSRF-TOKEN', // 默认值

  // `xsrfHeaderName` 是带有 xsrf token 值的http 请求头名称
  xsrfHeaderName: 'X-XSRF-TOKEN', // 默认值

  // `onUploadProgress` 允许为上传处理进度事件
  // 浏览器专属
  onUploadProgress: function (progressEvent) {
    // 处理原生进度事件
  },

  // `onDownloadProgress` 允许为下载处理进度事件
  // 浏览器专属
  onDownloadProgress: function (progressEvent) {
    // 处理原生进度事件
  },

  // `maxContentLength` 定义了node.js中允许的HTTP响应内容的最大字节数
  maxContentLength: 2000,

  // `maxBodyLength`(仅Node)定义允许的http请求内容的最大字节数
  maxBodyLength: 2000,

  // `validateStatus` 定义了对于给定的 HTTP状态码是 resolve 还是 reject promise。
  // 如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),
  // 则promise 将会 resolved,否则是 rejected。
  validateStatus: function (status) {
    return status >= 200 && status < 300; // 默认值
  },

  // `maxRedirects` 定义了在node.js中要遵循的最大重定向数。
  // 如果设置为0,则不会进行重定向
  maxRedirects: 5, // 默认值

  // `socketPath` 定义了在node.js中使用的UNIX套接字。
  // e.g. '/var/run/docker.sock' 发送请求到 docker 守护进程。
  // 只能指定 `socketPath` 或 `proxy` 。
  // 若都指定,这使用 `socketPath` 。
  socketPath: null, // default

  // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
  // and https requests, respectively, in node.js. This allows options to be added like
  // `keepAlive` that are not enabled by default.
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // `proxy` 定义了代理服务器的主机名,端口和协议。
  // 您可以使用常规的`http_proxy` 和 `https_proxy` 环境变量。
  // 使用 `false` 可以禁用代理功能,同时环境变量也会被忽略。
  // `auth`表示应使用HTTP Basic auth连接到代理,并且提供凭据。
  // 这将设置一个 `Proxy-Authorization` 请求头,它会覆盖 `headers` 中已存在的自定义 `Proxy-Authorization` 请求头。
  // 如果代理服务器使用 HTTPS,则必须设置 protocol 为`https`
  proxy: {
    protocol: 'https',
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // see https://axios-http.com/zh/docs/cancellation
  cancelToken: new CancelToken(function (cancel) {
  }),

  // `decompress` indicates whether or not the response body should be decompressed 
  // automatically. If set to `true` will also remove the 'content-encoding' header 
  // from the responses objects of all decompressed responses
  // - Node only (XHR cannot turn off decompression)
  decompress: true // 默认值

}

4 响应配置

一个请求的响应包含以下信息。

{
  // `data` 由服务器提供的响应
  data: {},

  // `status` 来自服务器响应的 HTTP 状态码
  status: 200,

  // `statusText` 来自服务器响应的 HTTP 状态信息
  statusText: 'OK',

  // `headers` 是服务器响应头
  // 所有的 header 名称都是小写,而且可以使用方括号语法访问
  // 例如: `response.headers['content-type']`
  headers: {},

  // `config` 是 `axios` 请求的配置信息
  config: {},

  // `request` 是生成此响应的请求
  // 在node.js中它是最后一个ClientRequest实例 (in redirects),
  // 在浏览器中则是 XMLHttpRequest 实例
  request: {}
}

5 拦截器

拦截器主要分为请求拦截器和响应拦截器

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
  });

二,封装准备工作

在正式开发前,首先需要清楚请求一个接口都做了什么。为此做了一个请求流程图,以便于我们后续进行需求分析。

1 基础请求流程

基础请求流程,我们大致可以分为三块, 一是 请求进入请求拦截前 、二是 真正发起的请求 、三是 请求从响应拦截出来后
这其中可以归为两类,
一类是 针对单独接口的处理 (查询文件接口,后台返回的是流文件)
二类是 **针对所有接口需要的内容 **(一般接口,返回的是json)

  • 针对单独接口的处理
    • 请求前的参数处理
    • 请求后的返回值处理
  • 针对所有接口的处理
    • Post
    • Get
    • Put
    • Del

2 拦截器

拦截器,我们大致可以分为两类, 一类是 请求接口前的统一处理(请求拦截) 、 一类是 请求接口后的统一处理(响应拦截)

  • 请求拦截:请求头调整,用户标识
  • 响应拦截:网络错误处理,授权错误处理,普通错误处理,代码异常处理

3 axios封装顺序

随着我们要做的内容越来越多,我们希望它有一个顺序以便于我们按部就班的开发,以便于我们按照流程,无意外的完成此次封装。
在我们的开发中,我们基本要遵循先处理通用内容在处理个性化内容的逻辑:

  1. 针对所有接口的处理(Get)
  2. 请求拦截
  3. 响应拦截
  4. 针对单独接口的处理
  5. 封包处理
  6. 针对所有接口的处理(Post、Put、Del)

三,进行axios二次封装

1 使用axios.create创建一个axios实例,

create方法接收一个可为空参数。

const instance = axios.create({
  baseURL: "http://localhost:3001", //统一地址前缀
  timeout: 60000   //设置超时时间
})

也可以这种写法

const config = {
  baseURL: "http://localhost:3001",
  timeout: 60000,
};
// 创建axios实例
let instance = axios.create();
//超时设置
instance.defaults.timeout = config.timeout;
instance.defaults.baseURL = config.baseURL;

查看axios实例的内容,axios的实例是一个函数

const service = axios.create({
        baseURL: 'http://localhost:3001',
        timeout: 60000
      })
console.log(service);
//结果
ƒ wrap() {
    var args = new Array(arguments.length);
    for (var i = 0; i < args.length; i++) {
      args[i] = arguments[i];
    }
    return fn.apply(thisArg, args);
  }

2 给axios的实例设置请求拦截器和响应拦截器,其接收两个方法,成功的回调和失败的回调

请求拦截器:

service.interceptors.request.use(
  config => {
    if (config.baseURL == undefined) {
      config.baseURL = getManageUrl();
    }
    if (!config.notShowLoading) {
      showLoading(config.loadingTarget)
    }
    config.headers['Accept'] = 'application/json'
    if (getTradeToken()) {
      config.headers['token'] = getTradeToken()
    }
    // 是否需要清空上一页面的请求
    config.cancelToken = new CancelToken(function (cancel) {
      if (config.headers.needCancel || typeof config.headers.needCancel == 'undefined') {
        store.commit('cancelToken/pushCancelToken', cancel)
      }
    });
    //移除请求
 //   removePendingRequest(config);
  //  addPendingRequest(config);
    return config
  },
  error => {
    Message.error('请求错误!')
    console.log(error)
    return Promise.reject(error)
  }
)

成功回调:
(1) 设置baseURL属性
(2) 根据设置属性开启遮罩
(3) 给请求头设置Accept属性
(4) 设置token验证
(5) 打开新界面时清空上一页面请求
失败回调:返回错误信息。

响应拦截器:

service.interceptors.response.use(
  response => {
    if (!response.config.notShowLoading) {
      hideLoading()
    }
    //移除请求
    if(fileType.indexOf(response.data.type) !== -1){
      return response;
    }else if(response.data.code !== 200){
      Message.error(response.data.message);
      return Promise.reject(response)
    }else{
      return response.data
    }
  },
  error => {
    Message.error('系统错误!')
    if (!error.config.notShowLoading) {
      hideLoading()
    }
    //移除请求
    removePendingRequest(error.config);
    return Promise.reject(error)
  }
)
export default service

成功回调:
(1) 根据配置的变量关闭遮罩
(2) 根据接口返回类型分类(普通接口,文件接口)
(3) 对状态码不对的接口数据进行处理,返回失败的promise
(4) 过滤返回的数据。
失败回调:
(1) 根据配置的变量关闭遮罩
(2) 错误信息处理

3 调用统一封装的接口

import request from '@/utils/axios/commonRequest';
export function getDicts({dict, flag, ismodify}) {
  return request({
    url: '/dict_combo/query?dicid='+dict+'&flag='+flag+'&ismodify='+ismodify,
    method: 'get'
  });
}

四,拓展

1 拦截器是可以设置多个:请求拦截器是从后向前执行,响应拦截器是从前向后执行。

2 request源码解析:

Axios构造函数中,创建两个实例属性,分别是defaults、interceptors
defaults表示配置对象,如果不是用户直接调用Axios,那这个属性值就是defaults.js模块暴露的默认值
interceptors:拦截器,定义了request和response拦截器属性分别表示请求和响应拦截器


function Axios(instanceConfig) {
  this.defaults = instanceConfig;
  this.interceptors = {
    request: new InterceptorManager(),
    response: new InterceptorManager()
  };
}


Axios.prototype.request = function request(config) {
  /*eslint no-param-reassign:0*/
  // Allow for axios('example/url'[, config]) a la fetch API

  // 支持axios(url, config)
  if (typeof config === 'string') {
    config = utils.merge({
      url: arguments[0]
    }, arguments[1]);
  }

  // 应用自定义配置
  config = utils.merge(defaults, {method: 'get'}, this.defaults, config);
  config.method = config.method.toLowerCase();

  // Hook up interceptors middleware
  // chain是一个数组,dispatchRequest是发送请求模块
  var chain = [dispatchRequest, undefined];

  // 请求拦截器处理
  this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
    chain.unshift(interceptor.fulfilled, interceptor.rejected);
  });

  // 响应拦截器处理
  this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
    chain.push(interceptor.fulfilled, interceptor.rejected);
  });
  
  //发起请求并处理拦截器
  var promise = Promise.resolve(config);
  while (chain.length) {
    promise = promise.then(chain.shift(), chain.shift());
  }

  return promise;
};

通过chain数组模拟堆栈顺序,请求拦截器在发送请求前,响应拦截器在请求成功后,而实现这个效果就是通过数组的顺序来实现的,request调用unshift将拦截器插入最前部,response调用push将拦截器推入尾部。
通过promise发起请求,形成链式调用,下一次promise依赖上一次promise的返回值。
流程图示意图如下:
axios链式调用.png

参考文章:

前端架构带你 封装axios,一次封装终身受益「美团后端连连点赞」 - 掘金 (juejin.cn)