Axios概述
首先,axios是基于promise用于浏览器和node.js的http客户端
特点
支持浏览器和node.js
支持promise
能拦截请求和响应
能转换请求和响应数据
能取消请求
自动转换json数据
浏览器端支持防止CSRF(跨站请求伪造)
一.安装
$ npm install axios
二、 例子
1.发起一个get请求
<input id="get01Id" type="button" value="get01"/>
<script>
$("#get01Id").click(function () {
axios.get('http://localhost:8080/user/findById?id=1')
.then(function (value) {
console.log(value);
})
.catch(function (reason) {
console.log(reason);
})
})
</script>
另外一种形式:
<input id="get02Id" type="button" value="get02"/>
<script>
$("#get02Id").click(function () {
axios.get('http://localhost:8080/user/findById', {
params: {
id: 1
}
})
.then(function (value) {
console.log(value);
})
.catch(function (reason) {
console.log(reason);
})
})
</script>
2.发起一个post请求
在官方文档上面是这样的:
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
}).then(function (res) {
console.log(res);
}).catch(function (err) {
console.log(err);
});
但是如果这么写,会导致后端接收不到数据
所以当我们使用post请求的时候,传递参数要这么写:
<input id="post01Id" type="button" value="post01"/>
<script>
$("#post01Id").click(function () {
var params = new URLSearchParams();
params.append('username', 'sertyu');
params.append('password', 'dfghjd');
axios.post('http://localhost:8080/user/addUser1', params)
.then(function (value) {
console.log(value);
})
.catch(function (reason) {
console.log(reason);
});
})
</script>
3.执行多个并发请求
<input id="button01Id" type="button" value="点01"/>
<script>
function getUser1() {
return axios.get('http://localhost:8080/user/findById?id=1');
}
function getUser2() {
return axios.get('http://localhost:8080/user/findById?id=2');
}
$("#buttonId").click(function () {
axios.all([getUser1(), getUser2()])
.then(axios.spread(function (user1, user2) {
alert(user1.data.username);
alert(user2.data.username);
}))
})
</script>
另外一种形式:
<input id="button02Id" type="button" value="点02"/>
<script>
$("#button02Id").click(function () {
axios.all([
axios.get('http://localhost:8080/user/findById?id=1'),
axios.get('http://localhost:8080/user/findById?id=2')
])
.then(axios.spread(function (user1, user2) {
alert(user1.data.username);
alert(user2.data.username);
}))
})
</script>
当所有的请求都完成后,会收到一个数组,包含着响应对象,其中的顺序和请求发送的顺序相同,可以使用axios.spread分割成多个单独的响应对象