您的位置:首页 > Web前端 > Vue.js

VUE常见问题 - AXIOS使用请求

2020-02-05 18:56 489 查看

发起一个get请求 

[code]<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>

另外一种形式:

[code]<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>

发起一个post请求

在官方文档上面是这样的:

[code]axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
}).then(function (res) {
console.log(res);
}).catch(function (err) {
console.log(err);
});

但是如果这么写,会导致后端接收不到数据

所以当我们使用post请求的时候,传递参数要这么写:

[code]<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>

行多个并发请求

[code]<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>

另外一种形式:

[code]<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>

原文连接: https://blog.csdn.net/qq_41033290/article/details/82844716

  • 点赞
  • 收藏
  • 分享
  • 文章举报
柠檬茶啊 发布了7 篇原创文章 · 获赞 0 · 访问量 947 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: