Axios是一个基于promise的HTTP库,可以用在浏览器和node.js中。
- 安装
- npm install axios --save
- cnpm install axios --save
- 使用CDN <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
- GET请求
axios.get('/getUserInfo?id=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 可选地,上面的请求可以这样做
axios.get('/getUserIngo', {
params: {
id: 1
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
- POST请求
axios.post('/user', {
firstName: 'newName',
lastName: 'lastName'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
- 执行多个并发请求
function getUserAccount() {
return axios.get('/getUserInfo/1');
}
function getUserPermissions() {
return axios.get('/getUserInfo/1/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// 两个请求现在都执行完成
}));