axios简介
axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:
- 从浏览器中创建 XMLHttpRequest
- 从 node.js 发出 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 自动转换JSON数据
- 客户端支持防止 CSRF/XSRF
安装
使用npm :
npm install axios
bower :
bower install axios
yarn:
yarn add axios
jsDelivr CDN:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
unpkg CDN:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
用例
发起一个get请求
const axios = require('axios');
// 向给定ID的用户发起请求
axios.get('/user?ID=12345')
.then(function (response) {
// 处理成功情况
console.log(response);
})
.catch(function (error) {
// 处理错误情况
console.log(error);
})
.finally(function () {
// 总是会执行
});
// 上述请求也可以按以下方式完成(可选)
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
// 总是会执行
});
// 支持async/await用法
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
发起一个post请求
axios.post('/user',{
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
执行多个并发请求
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
const [acct, perm] = await Promise.all([getUserAccount(), getUserPermissions()]);
// OR
Promise.all([getUserAccount(), getUserPermissions()])
.then(function ([acct, perm]) {
// ...
});
axios API
可以通过将相关配置传递给 axios 来进行请求
axios(config)
//发送一个post请求
axios({
method:'post',
url:'user/12345',
data:{
firstName:"Fred",
lastName:"Filintstone"
}
});
axios(url[,config])
//发送一个GET请求(GET请求是默认请求模式)
axios('/user/12345');