zroger's blog

axios 小结

ZRoger ZRoger #axios

Vue 项目里从 jQuery ajax 迁移到 axios 的实践小结:基础用法、并发请求,以及请求/响应拦截与 BaseApi 的分层封装。

工作的项目是前后端分离的,前端项目采用 Vue 相关的技术栈进行搭建,与此同时,前端请求的方式也发生了改变,由原来 Jquery 中 ajax 变为 axios ;

在使用的过程中当然存在一些疑问,在这里作下小小的汇总;

axios 是什么

GitHub 地址:https://github.com/axios/axios,aixos 是一个基于Promise的Http库,主要使用在浏览器和以node.js作为后端的应用中。安装和使用官网里已经有了,可以看下中文网的文档。

简单对比

两种库的请求:

// Jquery ajax post
$.ajax({
url: 'http://openapi.xx.com/xx/',
type: 'POST',
data:{
id:'123'
},
successs:function(result){
console.log(result)
}
}})
// axios
axios.post(
'http://openapi.xx.com/xx/',
{id:'123'}
).then(function(result){
console.log(result)
}).catch(function(error){
console.log(error)
})

执行多个并发请求

// 获取用户公开信息
function fetchUserInfo(userId) {
return axios.get("/user/" + userId);
}
// 获取用户设置偏好
function fetchUserPreference(userId) {
return axios.get("/user/" + userId + "/preference");
}
const userId = "123";
Promise.all([fetchUserInfo(userId), fetchUserPreference(userId)]).then(
res =>{
console.log(res[0], res[1])
}
);

项目中的封装

axios提供api来传递配置创建请求,所以可以进行一个简易的封装,方便前端统一管理接口。避免在main.js或者各个vue文件中重复引入axios;或者写相同的接口,如:axios.get('/user?ID=12345')。

简单封装 request.js

使用自定义配置创建一个axios实例,其他api.js使用这个实例进行创建

import axios from 'axios'
import qs from 'querystring'
// axios instance
const service = axios.create({
baseURL: 后端接口地址,
timeout: 10000
})
// 请求拦截
service.interceptors.request.use(.....)
// 响应拦截
service.interceptors.response.use(.....)
export default service

请求拦截,在 axios 中,post 请求中的数据会传递 json 形式的数据回到后端,即Content-Type为appliaction/json;后端的接口需要加上注解@RequestBody来接收json参数,为了兼容一下老的接口需要作一定的处理

// request interceptor
service.interceptors.request.use(
(config) => {
if (config.data instanceof FormData) {
// 文件
config.headers["Content-Type"] = "multipart/form-data";
} else if (config.dataType === "json") {
// 当要传递 json 形式的数据时,改变 content-type
config.headers["Content-Type"] = "application/json";
} else {
// get/post
config.headers["Content-Type"] = "application/x-www-form-urlencoded";
config.data = qs.stringify(config.data);
}
// config headers token
return config;
},
(error) => {
// do something with request error
return Promise.reject(error);
}
);

返回信息拦截

// response interceptor
service.interceptors.response.use(
(response) => {
return response.data;
},
(error) => {
if (error.response) {
if (error.response.status === 40001) {
// 返回登录页面
}
}
return Promise.reject(error);
}
);

使用 request.js

import request from "@/http/request";
export function fetchDemoPage(params) {
return request({
url: "/demo/page",
method: "get",
params,
});
}

为了方便维护前端 api 函数,在 vue 项目生成的 src 中创建api文件夹。

Terminal window
+---api
| +---public
| | +---sign

封装 BaseApi

随着写模块越来越多,自热而然会产生一些重复的代码,比如:

a-api.js

import request from '@/http/request'
export function fetchDemoAPage(params) {
return request({
url: '/a/page',
method: 'get',
params
})
}

b-api.js

import request from '@/http/request'
export function fetchDemoBPage(params) {
return request({
url: '/b/page',
method: 'get',
params
})
}

接口形式差不多,感觉可以抽离一个公共的 js 进行调整,当然这个封装的前提是前后端都约定后一些通用的接口形式

export default class BaseApi {
constructor(microservice, controller){
this.microservice = microservice
this.controller = controller
// 分页
this.page = BaseApi.get('page')
// 获取vo实体
this.fetchData = BaseApi.get('find')
// 删除实体
this.delData = BaseApi.post('delete')
.... 省略
}
static get(methodPath){
return function(params){
return request({
url: this.microservice + '/' + this.controller + '/' + methodPath,
method:'get',
params
})
}
}
static post(methodPath){
return function(data){
return request({
url: this.microservice + '/' + this.controller + '/' + methodPath,
method: 'post',
data
})
}
}
static postJson(..){...}
}

使用 BaseApi

user-sign.js 用户注册相关 api

import BaseApi from "@/api/base";
const api = new BaseApi("user", "sign");
// 自定义api
api.test = EntBaseApi.get("test/getReleaseList");
export default api;

其他:

其他一些比较重要的,就列在这里,来源官网

请求方法的别名

为方便起见,为所有支持的请求方法提供了别名

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

注意

在使用别名方法时, url、method、data 这些属性都不必在配置中指定。

并发

处理并发请求的助手函数

axios.all(iterable);
axios.spread(callback);

创建请求的配置

{
// `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 参数
// 必须是一个简单对象或 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 // 默认值
}

响应结构

{
// `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: {}
}

参考资料

  1. http://www.axios-js.com/zh-cn/docs/index.html
  2. https://github.com/PanJiaChen/vue-element-admin/blob/master/src/utils/request.js