vue axios封裝以及API統一管理
在vue專案中,每次和後台互動的時候,經常用到的就是axios請求資料,它是基於promise的http庫,可執行在瀏覽器端和node.js中。當專案越來越大的時候,介面的請求也會越來越多,怎麼去管理這些介面?多人合作怎麼處理?衹有合理的規劃,才能方便往後的維護以及修改,
安裝
安裝axios依賴包
1 | cnpm install axios --save |
引入
一般會我會在專案src中新建一個untils目錄,其中base用於管理介面網域名稱,http處理請求攔截和回應攔截,user.js負責介面檔案(介面檔案可以自己新建一個資料夾,然後放對應的介面檔案)
1.在http.js檔案中,用於處理axios中對請求攔截和回應攔截做處理,token處理,並引入element-ui載入影片。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | import axios from 'axios' import { Loading, Message } from 'element-ui' import router from '../router/index.js' let loading function startLoading() { loading = Loading.service({ lock: true, text: '載入中....', background: 'rgba(0, 0, 0, 0.7)' }) } function endLoading() { loading.close() } // 請求攔截 axios.interceptors.request.use( (confing) => { startLoading() //設定請求標頭 if (localStorage.eToken) { confing.headers.Authorization = localStorage.eToken } return confing }, (error) => { return Promise.reject(error) } ) //回應攔截 axios.interceptors.response.use( (response) => { endLoading() return response }, (error) => { Message.error(error.response.data) endLoading() // 取得狀態碼 const { status } = error.response if (status === 401) { Message.error('請重新登入') //清楚token localStorage.removeItem('eToken') //跳轉到登入頁面 router.push('/login') } return Promise.reject(error) } ) export default axios |
透過建立一個axios例項然後export default方法匯出,這樣使用起來更靈活一些。
2.在base.js檔案中,用於管理我們請求介面的網域名稱,極大的方便後期的維護和開發,如果以後更改網域名稱地址或者增加網域名稱,只需要修改這樣就可以了、
1 2 3 4 5 6 | //網域名稱統一管理 const base = { url: 'http://localhost:5001/api' } export default base |
3.介面統一管理,每一個js檔案都對應一個功能請求介面管理,在下面實現get,post的例項請求,並且引入qs序列化的處理,使用之前先安裝qs
1 2 | 安裝qs cnpm install qs --save |
3.1:更加模組化管理
3.2:更方便多人開發,有效減少解決命名衝突
3.3:處理介面網域名稱有多個情況
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import axios from '../untils/http' import QS from 'qs' import base from './base' /** * post方法,對應post請求 * @desc註冊請求 * @param {String} url [請求的url地址] * @param {Object} params [請求時攜帶的引數] */ export function userRejister(data) { return axios({ url: `${base.url}/users/register`, method: 'post', data: QS.stringify(data) }) } /** * get方法,對應get請求 * @desc登入請求 * @param {String} url [請求的url地址] * @param {Object} params [請求時攜帶的引數] */ export function userInfo() { return axios({ url: `${base.url}/profile/all`, method: 'get' }) } |
4.使用。以上工作做完之後,只需要在我們需要發送請求介面的檔案,引入
1 2 | 本例項中引入範例 import { userRejister} from "../../untils/user.js"; |
發送請求axios請求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | async submitForm(formName) { this.$refs[formName].validate(valid => { if (valid) { //發送請求return new Promise((resolve, reject) => { userRejister(this.registerUser) .then(response => { console.log(response); resolve(); }) .catch(error => { reject(error); }); }); } else { console.log("error submit!!"); return false; } }); }, |
轉載 : https://www.cnblogs.com/reeber/p/11267030.html