目录
基本使用
先说一下怎么安装和引入:
npm install axios --save
import axios from 'axios' //使用前引入
axios 有很多请求方式,具体可以看一下官网的 API,下面先学习最基本的使用方式。
发起一个 GET
请求
axios.get(url[, config])
import axios from 'axios'
// 向给定id的用户发起请求
axios.get('http://127.0.0.1:8000/user?id=1')
.then(function (res) {
// 处理成功情况
console.log(res);
})
.catch(function (error) {
// 处理错误情况
console.log(error);
})
.then(function () {
// 总是会执行
});
// 上述请求也可以按以下方式完成(可选)
axios.get('http://127.0.0.1:8000/user', {
params: {
id: 1
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// 总是会执行
});
// 支持async/await用法
async function getUser() {
try {
const res = await axios.get('http://127.0.0.1:8000/user?id=1');
console.log(res);
} catch (error) {
console.error(error);
}
}
发起一个 POST
请求
axios.post(url[, data[, config]])
axios.post('http://127.0.0.1:8000/user/add', {
name: 'stary',
age: 18
})
.then(function (res) {
console.log(res);
})
.catch(function (error) {
console.log(error);
});
发送并发请求
axios.all([])
返回的结果是一个数组,使用 axios.spread
可将数组 [res1,res2]
展开为 res1, res2
。
function getUserInfo() {
return axios.get('http://127.0.0.1:8000/user/1');
}
function getUserRole() {
return axios.get('http://127.0.0.1:8000/user/role?userId=1');
}
axios.all([getUserInfo(), getUserRole()])
.then(function (res) {
console.log(res[0])
console.log(res[1])
})
// 使用 `axios.spread`
axios.all([getUserInfo(), getUserRole()])
.then(
axios.spread((res1, res2) => {
console.log(res1)
console.log(res2)
})
);