Axios 笔记

Axios 笔记

Axios是一个易用、简洁且高效的http库

主要功能特点包括:

  • 从浏览器中创建XMLHttpRequests
  • 从NodeJS创建Http请求
  • 支持Promise API(链式编程)
  • 拦截请求和响应
  • 转换请求数据和响应数据
  • 取消请求
  • 自动转换JSON数据
  • 客户端支持防御XSRF(跨站请求伪造)

官网: https://axios-http.com/
GitHub: GitHub-Axios

安装

  • 使用npm
1
npm install axios
  • 使用bower
1
bower install axios
  • 使用yarn
1
yarn add axios
  • 使用CDN:
    jsDelivr:
1
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

unpkg

1
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

使用

1
const axios = require('axios').default;

发送一个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
const axios = require('axios');

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});

// Optionally the request above could also be done as
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});

// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}

发送一个POST请求

1
2
3
4
5
6
7
8
9
10
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

处理并发请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function getUserAccount() {
return axios.get('/user/12345');
}

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

Promise.all([getUserAccount(), getUserPermissions()])
.then(function (results) {
const acct = results[0];
const perm = results[1];
});

Axios API

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
// axios(config)
// Send a POST request
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});

// axios(config)
// GET request for remote image in node.js
axios({
method: 'get',
url: 'http://bit.ly/2mTM3nY',
responseType: 'stream'
})
.then(function (response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});


// axios(url [, config])
// Send a GET request (default method)
axios('/user/12345');