Axios 官方文档:https://axios-http.com/zh/docs/intro

CDN:<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

Json-Server

JSON-Server 是一个 Node 模块,运行 Express 服务器,你可以指定一个 json 文件作为 api 的数据源,详情戳Github。

Github:https://github.com/typicode/json-server

快速使用

安装

npm install -g json-server

创建

Create a db.json file with some data

1
2
3
4
5
6
7
8
9
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}

开启

Start JSON Server

json-server --watch db.json

效果

通过:http://localhost:3000/ 地址访问

20220821204547

Axios 特性

  1. 基于 xhr + promise 的异步 ajax 请求库
  2. 浏览器端 /node 端都可以使用
  3. 支持请求/响应拦截器
  4. 支持请求取消
  5. 请求 / 响应数据转换
  6. 批量发送多个请求

Axios API

  1. axios(config): 通用/最本质的发任意类型请求的方式
  2. axios(url[, config]): 可以只指定 url 发 get 请求
  3. axios.request(config): 等同于 axios(config)
  4. axios.get(url[, config]): 发 get 请求
  5. axios.delete(url[, config]): 发 delete 请求
  6. axios.post(url[, data, config]): 发 post 请求
  7. axios.put(url[, data, config]): 发 put 请求

请求配置

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
{
// `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 // 默认值

}

默认配置

可以指定默认配置,简化代码,它将作用于每个请求。

全局 axios 默认值

1
2
3
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

自定义实例默认值

1
2
3
4
5
6
7
// 创建实例时配置默认值
const instance = axios.create({
baseURL: 'https://api.example.com'
});

// 创建实例后修改默认值
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

配置的优先级

配置将会按优先级进行合并。它的顺序是:(后面的优先级要高于前面的)

  1. lib/defaults.js 中找到的库默认值
  2. 实例的 defaults 属性
  3. 请求的 config 参数

拦截器

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

请求拦截器:在发送请求之前,对请求的参数作一些处理和检测。
响应拦截器:在处理结果之前,可以对返回的数据作一些预处理。

添加拦截器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 添加请求拦截器
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
2
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

实例的拦截器

可以给自定义的 axios 实例添加拦截器。

1
2
const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});

取消请求

AbortController

从 v0.22.0 开始,Axios 支持以 fetch API 方式—— AbortController 取消请求:

1
2
3
4
5
6
7
8
9
const controller = new AbortController();

axios.get('/foo/bar', {
signal: controller.signal
}).then(function(response) {
//...
});
// 取消请求
controller.abort()

CancelToken【已弃用】

源码分析

源码目录结构

20220821230707

二次封装

参考:https://juejin.cn/post/7085253512572960781

针对项目大小的程度不同,对axios封装的需求也全然不同。
axios本身就是封装很不错的了,所以对于一般小项目而言完全没有二次封装的意义。
二次封装往往也会配合api的统一管理来进行使用。

尚品汇项目二次封装

主要是利用axios的拦截器(请求拦截器和响应拦截器)进行封装:

  1. 项目中安装 axios
  2. 项目中新建 src/api/request.js 文件
  3. 在 request.js 文件中编写:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    // src/api/request.js

    import axios from 'axios';
    // 1. 利用axios对象的方法create,去创建一个axios实例
    const service = axios.create({
    // 基础路径(发请求的时候,路径当中会出现api)
    baseURL: '/api',
    // 请求超时的时间 5S
    timeout: 5000,
    });

    // 2. 请求拦截器:在发请求之前,请求拦截器可以检测到,可以在请求发出去之前做一些事情
    service.interceptors.request.use(config => {
    return config;
    })

    // 3. 响应拦截器:所有的请求在响应之后都会走这个
    service.interceptors.response.use(
    // 成功的回调函数:服务器相应数据回来以后,响应拦截器可以检测到,可以做一些事情
    (res) => {
    return res.data;
    }, (err) => {
    //响应失败的回调函数
    return Promise.reject(new Error('faile'));
    })

    export default service;
  4. API 统一管理
    1. 项目中新建 src/api/index.js 文件,并导入二次封装好的 axios
    2. 基于二次封装好的 axios 发送请求:
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      // src/api/index.js

      import service from './request'
      // getBaseCategoryList
      export const getBaseCategoryList = () => {
      return service({
      url: "/product/getBaseCategoryList",
      method: "get"
      })
      }
  5. 解决跨域问题(devServer)
    项目根目录新建 vue.config.js 文件 :
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    module.exports = {
    // 配置此项,打包时不生成 map 文件
    productionSourceMap: false,
    lintOnSave: false,
    devServer: {
    proxy: {
    '/api': {
    target: 'http://gmall-h5-api.atguigu.cn', // 代理目标的基础路径
    // pathRewrite: {
    // '^/api': ''
    // }
    }
    }
    }
    }