使用方法

1
2
3
4
5
6
7
8
9
// 发送 post
axios({
method: 'post',
url: 'url',
data: { key:value }
})

// 发送 get 默认方法
axios('url')

支持请求别名

axios.request(config)
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]])

并发使用

1
2
3
4
5
6
7
8
9
10
axios.all(iterable)
axios.spread(callback)

var me = this
this.$axios.all([me.getAllTask(), me.getAllCity()])
.then(me.$axios.spread(function(allTask, allCity){
console.log('所有请求完成')
console.log('请求1', allTask)
console.log('请求2', allCity)
}))

创建实例

1
2
3
4
5
var instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
})

请求配置参数

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
{
// 请求服务器地址
url: '/user/info',

// 请求方法, 默认 get
method: 'get',

// baseUrl 自动添加在 url 前面,除非 url 是一个绝对地址
baseURL: 'https://www.xxx.com/api/',

// transformRequest 允许发送数据到服务器前,处理数据
// 只能用在 put、post、patch 这几个方法
// 后面数组中函数返回必须字符串、ArrayBuffer、Stream
transformRequest: [
function (data) {
return data
}],

// transformRespone 传递给 then/catch 前,允许修改响应数据
transformRespone: [
function (data) {
return data
}],

// headers 自定义请求头
headers: {'X-Requested-With': 'XMLHttpRequest'}

// params 参数
params: {
id: 12
},

// paramsSerializer params 序列化函数
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},

// 请求主体被发送的数据
// 只适用于 put、post、patch
// 没有设置 transformRequest 数据类型必须以下之一:
// string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// 浏览器专属: formdata, file, blob
// node专属: stream
data: {}

// timeout 请求超时
timeout: 1000,

// 表示跨域请求是否需要凭证
withCredentials: false,

// 自定义处理请求
adapter: function(config){},

// 适用 HTTP 基础验证,提供凭据
// 设置一个 Authorization 重写 headers 设置的自定义 Authorization 头
auth: {
username: 'janedoe',
password: 's00pers3cret'
},

// 服务器响应数据类型,arraybuffer、blob、document、json、text、stream
responseType: 'json',

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

// `xsrfHeaderName` 是承载 xsrf token 的值的 HTTP 头的名称
xsrfHeaderName: 'X-XSRF-TOKEN', // 默认

// 允许上传处理进度事件
onUploadProgress: function (progressEvent) {
// 对原生进度事件的处理
},

// 允许下载处理进度事件
onDownloadProgress: function (progressEvent) {
// 对原生进度事件的处理
},

// 定义允许的响应内容的最大尺寸
maxContentLength: 2000,

// HTTP 响应状态码验证
// 返回 `true` (`null`、`undefined`),promise 将被 resolve; 否则 promise 将被 rejecte
validateStatus: function (status) {
return status >= 200 && status < 300; // 默认
},

// 定义在 node.js 中 follow 的最大重定向数目
maxRedirects: 5 // 默认

// node.js 中用于定义在执行 http 和 https 时使用的自定义代理
// keepAlive 默认没有启用
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),

// proxy 定义代理服务器的主机名称和端口
// auth 表示 HTTP 基础验证应当用于连接代理,并提供凭据
// 这将会设置一个 Proxy-Authorization 头,覆写 header 设置的自定义 Proxy-Authorization 头。
proxy: {
host: '127.0.0.1',
port: 9000,
auth: : {
username: 'mikeymike',
password: 'rapunz3l'
}
},

// 取消请求的 cancel token
cancelToken: new CancelToken(function (cancel) {
})
}

响应结构

1
2
3
4
5
6
7
{
data: {}, // 由服务器提供的响应
status: 200, // 来自服务器响应的 HTTP 状态码
statusText: 'OK', // 来自服务器响应的 HTTP 状态信息
headers: {}, // 服务器响应的头
config: {} // 是为请求提供的配置信息
}

配置的默认值

全局默认值

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';

自定义实例默认值

// 创建实例时设置配置的默认值
var instance = axios.create({
  baseURL: 'https://api.example.com'
})

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

配置优先级

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

拦截器

请求或响应被 then、catch 处理前拦截处理

1
2
3
4
5
6
7
8
9
10
11
12
// 请求拦截器
axios.interceptors.request.use(function(config){
return config
}, function(error){
return Promise.reject(error)
})
// 响应拦截器
axios.interceptors.response.use(function(response){
return config
}, function(error){
return Promise.reject(error)
})

var instance = axios.create();
instance.interceptors.request.use(function () { .. });

移除拦截器

axios.interceptors.request.eject(instance)

错误处理

1
2
3
4
5
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // 状态码在大于或等于`500`时才会 reject
}
})

validateStatus 配置选项定义一个自定义 HTTP 状态码的错误范围

官方文档

params和data区别

params 添加到url的请求字符串,一般用于 get 请求

传递的都是字符串,无法传递参数中包含json格式的数据

data 添加到请求体(body)中的,一般用于 post 请求

data 不可以用于 get 请求。