項目用到axios,記錄下簡單用法
1.普通get請求
axios.get('http://127.0.0.1:8080/test/delUser?userId='+id)
.then((response) => {
console.log(response.data);//請求的返回體
})
.catch((error) => {
console.log(error);//異常
});
參數傳遞也可以這樣寫
axios.get('http://127.0.0.1:8080/test/delUser',{
params: {
userId: id,
}
})
.then((response) => {
console.log(response.data);//請求的返回體
})
.catch((error) => {
console.log(error);//異常
});
2.post請求寫法
axios.post('http://127.0.0.1:8080/test/login', {
name: "admin",
pwd: "123456"
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
這時候的post請求使用這這種請求,Spring MVC中直接@RequestParam 接收參數是接受不到的
打開瀏覽器開發者工具會發現Request-Headers的Content-Type是application/json;charset=UTF-8
如果不想使用application/json的解決方式:
let param = new URLSearchParams();//使用URLSearchParams傳參數
param.append("name", "admin");
param.append("pwd", "123456");
axios.post('http://127.0.0.1:8080/test/login',param)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
3.一次性併發多個請求
function getListOne(){
return axios.get('http://127.0.0.1:8080/test/getListOne');
}
function getListTwo(){
return axios.get('http://127.0.0.1:8080/test/getListOne');
}
axios.all([getListOne(),getListTwo()])
.then(axios.spread(function(acct,perms){
//兩個請求都成功觸發這個函數,兩個參數代表兩次請求返回的結果
}))
4.PS:axios不支持同步請求,可以使用請求成功之後再操作的方式代替同步請求