在前端開發的專案當中,與后端進行資料互動,請求后端資料是一個必不可少的作業,當前前端開發作業中,通常使用axios插件向后端拿資料,Axios 是一個基于 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中,axios有很多的有點,這里就不一一一一熬述,有興趣的讀者可以自行搜索,如果直接使用axios,比如:
npm install axios
or
yarn add axios
需要對axios的請求、回應進行二次封裝, 會多一道作業,作為一名程式員,切記不要重復造輪子,
在vue專案當中,可以使用vue-axios-plugin插件,
npm 模塊引入
首先通過 npm 安裝
npm install --save vue-axios-plugin
or
yarn add vue-axios-plugin
然后在入口檔案配置如下:
import Vue from 'Vue'
import VueAxiosPlugin from 'vue-axios-plugin'
Vue.use(VueAxiosPlugin, {
// 請求攔截處理
reqHandleFunc: config => config,
reqErrorFunc: error => Promise.reject(error),
// 回應攔截處理
resHandleFunc: response => response,
resErrorFunc: error => Promise.reject(error)
})
配置引數
除了 axios 提供的默認 請求配置, vue-axios-plugin 也提供了 request/response 攔截器配置,如下:
| 引數名 | 型別 | 默認值 | 描述 |
|---|---|---|---|
reqHandleFunc | {Function} | config => config | 請求發起前的攔截處理函式 |
reqErrorFunc | {Function} | error => Promise.reject(error) | 處理請求錯誤的函式 |
resHandleFunc | {Function} | response => response | 回應資料處理函式 |
resErrorFunc | {Function} | error => Promise.reject(error) | 回應錯誤處理函式 |
示例
在 Vue 組件上添加了 $http 屬性, 它默認提供 get 和 post 方法,使用如下:
this.$http.get(url, data, options).then((response) => {
console.log(response)
})
this.$http.post(url, data, options).then((response) => {
console.log(response)
})
你也可以通過 this.$axios 來使用 axios 所有的 api 方法,如下:
this.$axios.get(url, data, options).then((response) => {
console.log(response)
})
this.$axios.post(url, data, options).then((response) => {
console.log(response)
})
每個請求方法可以傳入三個引數,第一個引數url多介面地址,第二引數是介面請求引數,那么,第三個引數是干什么用的呢?
如果一個專案當中,需要配置多個請求介面的話,該如何做呢?
如果使用vue-axios-plugin插件的話,會很方便的解決這個問題,這個時候就需要用到請求方法的第三個引數,
首先要明白,第三個引數的型別是物件或者陣列(有疑問,自行研究);
例如:
const data = {
phone: 'renlei',
code: '12'
};
const option = {
interfaceType: 'first'
};
this.$http.get('/cardLists', data, option).then(response => {
console.log(response);
});
const option1 = {
interfaceType: 'second'
};
this.$http.post('/login', data, option1).then(response => {
console.log(response);
});
這里我分別使用了get和post請求,并且都給其傳入了第三個引數,這個第三個引數都是物件,物件里面只有一個鍵值對,鍵interfaceType相同,但是值不同,
然后在配置vue-axios-plugin的檔案當中使用傳入的第三個引數,例如:
// 請求攔截處理
reqHandleFunc: config => {
console.log(config.interfaceType === 'first');
/* config.baseURL =
process.env.NODE_ENV === 'production'
? 'https://www.520mg.com'
: 'http://rap2api.taobao.org/app/mock/254896/'; */
let url = 'http://129.168.1.87/first';
if (config.interfaceType === 'first') {
url = 'http://129.168.1.87/first';
} else if (config.interfaceType === 'second') {
url = 'http://129.168.30.85/second';
}
config.baseURL = url;
config.headers['Content-Type'] = 'application/json';
config.headers.Accept = 'application/json';
config.retry = 4;
config.retryDelay = 1000;
config.timeout = 60000;
return config;
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/229891.html
標籤:其他
