淄博網(wǎng)站制作高端網(wǎng)絡(luò)登錄百度app
Vue + Element UI 實(shí)現(xiàn)權(quán)限管理系統(tǒng) 前端篇(三):工具模塊封裝?
封裝 axios 模塊
封裝背景
使用axios發(fā)起一個請求是比較簡單的事情,但是axios沒有進(jìn)行封裝復(fù)用,項目越來越大,會引起越來越多的代碼冗余,讓代碼變得越來越難維護(hù)。所以我們在這里先對 axios 進(jìn)行二次封裝,使項目中各個組件能夠復(fù)用請求,讓代碼變得更容易維護(hù)。
封裝要點(diǎn)
- 統(tǒng)一 url 配置
- 統(tǒng)一 api 請求
- request (請求) 攔截器,例如:帶上token等,設(shè)置請求頭
- response (響應(yīng)) 攔截器,例如:統(tǒng)一錯誤處理,頁面重定向等
- 根據(jù)需要,結(jié)合 Vuex 做全局的 loading 動畫,或者錯誤處理
- 將 axios 封裝成 Vue 插件使用
文件結(jié)構(gòu)
在 src 目錄下,新建一個 http 文件夾,用來存放 http 交互 api 代碼。
config.js:axios 默認(rèn)配置,包含基礎(chǔ)路徑等信息。
axios.js:二次封裝 axios 模塊,包含攔截器等信息。
interface.js?:請求接口匯總模塊,聚合模塊 API。
index.js:將 axios 封裝成插件,按插件方式引入。
config.js
export default {method: 'get',// 基礎(chǔ)url前綴baseURL: 'http://localhost:8080/',// 請求頭信息headers: {'Content-Type': 'application/json;charset=UTF-8'},// 參數(shù)data: {},// 設(shè)置超時時間timeout: 10000,// 攜帶憑證withCredentials: true,// 返回數(shù)據(jù)類型responseType: 'json' }
axios.js
import axios from 'axios'; import config from './config'; import qs from 'qs'; import Cookies from "js-cookie"; import router from '@/router'// 使用vuex做全局loading時使用 // import store from '@/store'export default function $axios(options) {return new Promise((resolve, reject) => {const instance = axios.create({baseURL: config.baseURL,headers: {},transformResponse: [function (data) {}]})// request 攔截器instance.interceptors.request.use(config => {let token = Cookies.get('token')// 1. 請求開始的時候可以結(jié)合 vuex 開啟全屏 loading 動畫// console.log(store.state.loading)// console.log('準(zhǔn)備發(fā)送請求...')// 2. 帶上tokenif (token) {config.headers.accessToken = token} else {// 重定向到登錄頁面router.push('/login')}// 3. 根據(jù)請求方法,序列化傳來的參數(shù),根據(jù)后端需求是否序列化if (config.method === 'post') {if (config.data.__proto__ === FormData.prototype|| config.url.endsWith('path')|| config.url.endsWith('mark')|| config.url.endsWith('patchs')) {} else {config.data = qs.stringify(config.data)}}return config},error => {// 請求錯誤時console.log('request:', error)// 1. 判斷請求超時if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {console.log('timeout請求超時')// return service.request(originalRequest);// 再重復(fù)請求一次}// 2. 需要重定向到錯誤頁面const errorInfo = error.responseconsole.log(errorInfo)if (errorInfo) {error = errorInfo.data // 頁面那邊catch的時候就能拿到詳細(xì)的錯誤信息,看最下邊的Promise.rejectconst errorStatus = errorInfo.status; // 404 403 500 ...router.push({path: `/error/${errorStatus}`})}return Promise.reject(error) // 在調(diào)用的那邊可以拿到(catch)你想返回的錯誤信息})// response 攔截器instance.interceptors.response.use(response => {let data;// IE9時response.data是undefined,因此需要使用response.request.responseText(Stringify后的字符串)if (response.data == undefined) {data = JSON.parse(response.request.responseText)} else {data = response.data}// 根據(jù)返回的code值來做不同的處理switch (data.rc) {case 1:console.log(data.desc)break;case 0:store.commit('changeState')// console.log('登錄成功')default:}// 若不是正確的返回code,且已經(jīng)登錄,就拋出錯誤// const err = new Error(data.desc)// err.data = data// err.response = response// throw errreturn data},err => {if (err && err.response) {switch (err.response.status) {case 400:err.message = '請求錯誤'breakcase 401:err.message = '未授權(quán),請登錄'breakcase 403:err.message = '拒絕訪問'breakcase 404:err.message = `請求地址出錯: ${err.response.config.url}`breakcase 408:err.message = '請求超時'breakcase 500:err.message = '服務(wù)器內(nèi)部錯誤'breakcase 501:err.message = '服務(wù)未實(shí)現(xiàn)'breakcase 502:err.message = '網(wǎng)關(guān)錯誤'breakcase 503:err.message = '服務(wù)不可用'breakcase 504:err.message = '網(wǎng)關(guān)超時'breakcase 505:err.message = 'HTTP版本不受支持'breakdefault:}}console.error(err)return Promise.reject(err) // 返回接口返回的錯誤信息})// 請求處理instance(options).then(res => {resolve(res)return false}).catch(error => {reject(error)})}) }
interface.js
import axios from './axios'/* * 將所有接口統(tǒng)一起來便于維護(hù)* 如果項目很大可以將 url 獨(dú)立成文件,接口分成不同的模塊*/// 單獨(dú)導(dǎo)出 export const login = () => {return axios({url: '/login',method: 'get'}) }export const getUser = () => {return axios({url: '/user',method: 'get'}) }export const getMenu = data => {return axios({url: '/menu',method: 'post',data}) }// 默認(rèn)全部導(dǎo)出 export default {login,getUser,getMenu }
index.js
// 導(dǎo)入所有接口 import apis from './interface'const install = Vue => {if (install.installed)return;install.installed = true;Object.defineProperties(Vue.prototype, {// 注意,此處掛載在 Vue 原型的 $api 對象上$api: {get() {return apis}}}) }export default install
安裝 js-cookie
上面 axios.js 中,會用到 Cookie 獲取 token,所以需要把相關(guān)依賴安裝一下。
執(zhí)行以下命令,安裝依賴包。
yarn add js-cookie
代碼實(shí)例
1.引入插件
在 main.js 中以 vue 插件的形式引入 axios,這樣在其他地方就可通過?this.$api 調(diào)用相關(guān)的接口了。
2.編寫接口
在 interface.js 中添加 login 接口。
3.調(diào)用接口
在登錄界面 Login.vue 中,添加一個登錄按鈕,點(diǎn)擊處理函數(shù)通過 axios 調(diào)用 login 接口返回數(shù)據(jù)。
成功返回之后,將 token 放入 Cookie 并跳轉(zhuǎn)到主頁。
<template><div class="page"><h2>Login Page</h2><el-button type="primary" @click="login()">登錄</el-button></div> </template><script>import mock from '@/mock/mock.js';import Cookies from "js-cookie";import router from '@/router'export default {name: 'Login',methods: {login() {this.$api.login().then(function(res) {alert(res.data.token)Cookies.set('token', res.data.token) // 放置token到Cookie router.push('/') // 登錄成功,跳轉(zhuǎn)到主頁}).catch(function(res) {alert(res);});}}} </script>
4.mock 接口
在 mock.js 中添加 login 接口進(jìn)行攔截,返回一個 token。
啟動測試
瀏覽器訪問:http://localhost:8080/#/login,顯示登錄界面。
點(diǎn)擊登錄按鈕,首先彈出框,顯示返回的 token 信息。
點(diǎn)擊確定關(guān)掉彈出框后,跳轉(zhuǎn)到主頁。點(diǎn)擊用戶、菜單按鈕,接口調(diào)用正常。
封裝 mock 模塊
為了統(tǒng)一可以統(tǒng)一管理和集中控制數(shù)據(jù)模擬接口,我們對 mock 模塊進(jìn)行了封裝,可以方便的定制模擬接口的統(tǒng)一開關(guān)和個體開關(guān)。
文件結(jié)構(gòu)
在 mock 目錄下新建一個 index.js ,創(chuàng)建 modules 目錄并在里面創(chuàng)建三個模塊 *.js 文件。
index.js:模擬接口模塊聚合文件
login.js:登錄相關(guān)的接口模擬
user.js:用戶相關(guān)的接口模擬
menu.js:菜單相關(guān)的接口模擬
index.js
import Mock from 'mockjs' import * as login from './modules/login' import * as user from './modules/user' import * as menu from './modules/menu'// 1. 開啟/關(guān)閉[業(yè)務(wù)模塊]攔截, 通過調(diào)用fnCreate方法[isOpen參數(shù)]設(shè)置. // 2. 開啟/關(guān)閉[業(yè)務(wù)模塊中某個請求]攔截, 通過函數(shù)返回對象中的[isOpen屬性]設(shè)置. fnCreate(login, true) fnCreate(user, true) fnCreate(menu, true)/*** 創(chuàng)建mock模擬數(shù)據(jù)* @param {*} mod 模塊* @param {*} isOpen 是否開啟?*/ function fnCreate (mod, isOpen = true) {if (isOpen) {for (var key in mod) {((res) => {if (res.isOpen !== false) {Mock.mock(new RegExp(res.url), res.type, (opts) => {opts['data'] = opts.body ? JSON.parse(opts.body) : nulldelete opts.bodyconsole.log('\n')console.log('%cmock攔截, 請求: ', 'color:blue', opts)console.log('%cmock攔截, 響應(yīng): ', 'color:blue', res.data)return res.data})}})(mod[key]() || {})}} }
login.js
// 登錄接口 export function login () {return {// isOpen: false,url: 'http://localhost:8080/login',type: 'get',data: {'msg': 'success','code': 0,'data': {'token': '4344323121398'// 其他數(shù)據(jù)}}} }
user.js
// 獲取用戶信息 export function getUser () {return {// isOpen: false,url: 'http://localhost:8080/user',type: 'get',data: {'msg': 'success','code': 0,'data': {'id': '@increment', 'name': '@name', // 隨機(jī)生成姓名'email': '@email', // 隨機(jī)生成姓名'age|10-20': 12// 其他數(shù)據(jù)}}} }
menu.js
// 獲取菜單信息 export function getMenu () {return {// isOpen: false,url: 'http://localhost:8080/menu',type: 'get',data: {'msg': 'success','code': 0,'data': {'id': '@increment', 'name': 'menu', // 隨機(jī)生成姓名'order|10-20': 12// 其他數(shù)據(jù)}}} }
修改引入
Login.vue
Home.vue
啟動測試
瀏覽器訪問:http://localhost:8080/#/,按照先前流程走一遍,沒有問題。