首先矿筝,目錄結(jié)構(gòu)如圖:
image.png
第一步端铛,安裝axios: npm install axios --save
第二步,創(chuàng)建config.js潮尝、index.js毅臊、interface.js等文件
第三步理茎,需要將mian.js中加入如下代碼:
import api from './http/index'
Vue.use(api)
axios.js:二次封裝axios模塊,包含攔截器等信息管嬉;
config.js:axios默認(rèn)配置皂林,包含基礎(chǔ)路徑等信息;
index.js:將axios封裝成插件蚯撩,按插件方式引入础倍;
interface.js:請(qǐng)求接口匯總模塊,聚合模塊API胎挎;
modules下存放模塊下的請(qǐng)求沟启,下面以LoginManage.js為例扰楼;
config.js的代碼如下:
export default {
method: 'post',
// 請(qǐng)求頭信息
headers: {
'Content-Type': 'application/json'
},
// 參數(shù)
data: {},
// 設(shè)置超時(shí)時(shí)間
timeout: 3000000,
// 攜帶憑證
withCredentials: true,
// 返回?cái)?shù)據(jù)類型
responseType: 'json'
}
interface.js代碼如下:
/*
* 用戶授權(quán)接口集合
*/
import * as PermissionManage from './modules/UserPermissionManage/PermissionManage'
import * as RoleManage from './modules/UserPermissionManage/RoleManage'
import * as UserManage from './modules/UserPermissionManage/UserManage'
import * as LoginManage from './modules/UserPermissionManage/LoginManage'
// 默認(rèn)全部導(dǎo)出
export default {
PermissionManage,
RoleManage,
UserManage,
LoginManage,
}
index.js代碼如下:
// 導(dǎo)入所有接口
import apis from './interface'
const install = Vue => {
if (install.installed)
return;
install.installed = true;
Object.defineProperties(Vue.prototype, {
// 注意,此處掛載在 Vue 原型的 $api 對(duì)象上
$api: {
get() {
return apis
}
}
})
}
export default install
axios.js代碼如下:(根據(jù)自己的需要參考即可)
import axios from 'axios';
import config from './config';
import router from '@/router';
import Vue from 'vue';
export default function $axios(options) {
return new Promise(
(resolve, reject) => {
const instance = axios.create({
baseURL: Vue.prototype.BASE_URL,
headers: options.config==undefined?config.headers:options.config,
timeout: config.timeout,
withCredentials: config.withCredentials
})
//添加請(qǐng)求攔截器
instance.interceptors.request.use(
config => {
let token = sessionStorage.getItem('token');
// 根據(jù)請(qǐng)求方法美浦,序列化傳來的參數(shù)弦赖,根據(jù)后端需求是否序列化
if (config.method == 'post') {
config.data=config.params
config.params=''
}
if(config.url.split("/")[0]=='api'||config.url.split("/")[1]=='isTelValid'||config.url.split("/")[1]=='getPhotoValidCode'||config.url.split("/")[1]=='sendMessage'){//不需要驗(yàn)證token
//某些不需要登錄也可以訪問的方法,不需要axios攔截浦辨。
console.log("此方法token不校驗(yàn)蹬竖,axios不攔截!")
return config;
}else{
if (token) {
config.headers.token = token
} else {
//清空sessionStorage流酬、store
// 重定向到登錄頁面
router.push('/login')
}
}
return config
},
error => {
// 請(qǐng)求錯(cuò)誤時(shí)
console.log('request:', error)
// 1. 判斷請(qǐng)求超時(shí)
if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
alert('timeout請(qǐng)求超時(shí)')
// 重定向到登錄頁面
router.push('/login')
// return service.request(originalRequest);// 再重復(fù)請(qǐng)求一次
}
// 2. 需要重定向到錯(cuò)誤頁面
const errorInfo = error.response
console.log(errorInfo)
if (errorInfo) {
error = errorInfo.data // 頁面那邊catch的時(shí)候就能拿到詳細(xì)的錯(cuò)誤信息,看最下邊的Promise.reject
const errorStatus = errorInfo.status; // 404 403 500 ...
router.push({
path:'/404'
})
}
return Promise.reject(error) // 在調(diào)用的那邊可以拿到(catch)你想返回的錯(cuò)誤信息
}
)
// 添加響應(yīng)攔截器
instance.interceptors.response.use(
response => {
let data;
let url=response.config.url.split("/");
let len=url.length;
// IE9時(shí)response.data是undefined币厕,因此需要使用response.request.responseText(Stringify后的字符串)
if (response.data == undefined) {
data = JSON.parse(response.request.responseText)
}else if(url[len-1]=='downloadLicenseFile'||url[len-1]=='downloadPrintFile'||url[len-1]=='getPhotoValidCode'||url[len-1]=='exportFile'){//返回為文件流、圖片流
data=response
} else {
data = response.data
}
// 根據(jù)返回的code值來做不同的處理
switch (data.result) {
case 2:
sessionStorage.clear();
router.push('/login');
break;
case 1:
console.log(data.msg)
break;
case 0:
console.log(data.msg)
break;
default:
}
return data
},
err => {
if (err && err.response) {
switch (err.response.status) {
case 400:
err.message = '請(qǐng)求錯(cuò)誤'
break
case 401:
err.message = '未授權(quán)芽腾,請(qǐng)登錄'
break
case 403:
err.message = '拒絕訪問'
break
case 404:
err.message = `請(qǐng)求地址出錯(cuò): ${err.response.config.url}`
break
case 408:
err.message = '請(qǐng)求超時(shí)'
break
case 500:
err.message = '服務(wù)器內(nèi)部錯(cuò)誤'
break
case 501:
err.message = '服務(wù)未實(shí)現(xiàn)'
break
case 502:
err.message = '網(wǎng)關(guān)錯(cuò)誤'
break
case 503:
err.message = '服務(wù)不可用'
break
case 504:
err.message = '網(wǎng)關(guān)超時(shí)'
break
case 505:
err.message = 'HTTP版本不受支持'
break
default:
}
}
return Promise.reject(err) // 返回接口返回的錯(cuò)誤信息
}
)
// 請(qǐng)求處理
instance(options).then(res => {
resolve(res)
return false
}).catch(error => {
reject(error)
})
})
}
LoginManage.js的代碼:
import axios from '../../axios'
/*
* 用戶登錄模塊
*/
// 檢查是否開啟手機(jī)驗(yàn)證
export const checkIsTelVerify = (params) => {
return axios({
url: 'loginInfo/isTelValid',
method: 'post',
params
})
}
// 獲取圖片驗(yàn)證碼
export const getPhotoValidCode = (params) => {
return axios({
url: 'loginInfo/getPhotoValidCode',
responseType: "arraybuffer",
method: 'post',
params
})
}
我們?cè)赩ue頁面就可以通過如下代碼調(diào)用方法(以此為例)
//檢查用戶是否開啟手機(jī)驗(yàn)證
var isOpenTelValide=(rule,value,callback) =>{
//檢查用戶是否開啟手機(jī)驗(yàn)證
let params={
"data":{
"userCode":value
}
}
this.$api.LoginManage.checkIsTelVerify(params).then((res)=>{
if(res.result==0){
if(res.data.isValid==0){
this.isOpen=false;
}else if(res.data.isValid==1){
this.isOpen=true;//用戶開啟了手機(jī)驗(yàn)證
}
}
})
};