###

简单来说,axiosvue-resource的替代品,基于Promise的HTTP请求库,适用于浏览器端和node.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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

// Optionally the request above could also be done as
axios.get('/user', {
params: { // 参数需要在默认的params对象中
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});


//Performing a POST request
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

//Performing multiple concurrent requests
function getUserAccount() {
return axios.get('/user/12345');
}

function getUserPermissions() {
return axios.get('/user/12345/permissions');
}

//等待两个请求都完成
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// Both requests are now complete
}));

POST 注意点

axios在post请求时,默认会将参数传递为JSON,所以如果要用 application/x-www-form-urlencoded 传送数据,需要额外处理

  • 利用URLSearchParams

    1
    2
    3
    4
    var params = new URLSearchParams();
    params.append('param1', 'value1');
    params.append('param2', 'value2');
    axios.post('/foo', params);
  • 利用qs

1
2
3
4
5
//全局设置参数格式
axios.defaults.transformRequest = [function (data) {
data = qs.stringify(data);
return data;
}] ;

拦截器

拦截器可以拦截 responerequest, 即拦截请求内容和响应结果。
比如:对于respone,约定了返回data中如果type:'login', 表示处于未登录状态,需要跳转登录页,则可以进行一个interceptores设置,避免每一个请求都重复设置。

1
2
3
4
5
6
7
8
9
10
axios.interceptors.response.use(function (response) {
// Do something before request is sent
if ( response.data.type === 'login' ){
// 跳转登录页
}
return response;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});

关于多实例

axios支持多实例,以满足项目中不同的请求设置。 根据需要,可以设置不同的请求实例。

1
2
3
4
5
var instance1 = axios.create();
instance1.defaults.baseURL = 'http://localhost:8888' ;

var instance2 = axios.create();
instance2.defaults.baseURL = 'https://localhost:8888' ;