基于Axios 常用的請求方法別名(詳解)
Axios
是一個基于 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中。
常用的請求方法別名一般有: Get/post/http協(xié)議請求
執(zhí)行Get請求
function get(){
return axios.get('/data.json', {
params:{
id:1234
}
}).then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
使用get方法進行傳參數(shù)的時候用的是 params方法
執(zhí)行Post請求
function post(){
return axios.post('/data.json', {
id:1234
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
使用post方法進行傳參數(shù)的時候是直接進行數(shù)據(jù)的傳遞,這也是兩種方法的區(qū)別。
執(zhí)行http協(xié)議請求
function http(){
return axios({
method: 'post',
url: '/data.json',
data: {
id: 1111,
},
params: {
id:2222,
}).then(res=>{
this.msg=res.data;
});
}
注意這里的區(qū)別,當使用post請求的時候,進行數(shù)據(jù)的傳參使用的是data方法,而使用get請求的時候,使用的是params方法。
使用攔截器:
在請求或響應被 then 或 catch 處理前攔截它們。
// 添加請求攔截器
mounted:function(){
axios.interceptors.request.use(function (config) {
// 在發(fā)送請求之前做些什么
return config;
}, function (error) {
// 對請求錯誤做些什么
return Promise.reject(error);
});
// 添加響應攔截器
axios.interceptors.response.use(function (response) {
// 對響應數(shù)據(jù)做點什么
return response;
}, function (error) {
// 對響應錯誤做點什么
return Promise.reject(error);
});
}
以上這篇基于Axios 常用的請求方法別名(詳解)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

