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