最近在項(xiàng)目中要用到攔截器,坦白說(shuō)是第一次聽說(shuō)這玩意,所以資料查了好久望抽,現(xiàn)在也算是明白了攔截器的作用加矛。我的理解就是攔截每一次你的請(qǐng)求和響應(yīng),然后進(jìn)行相應(yīng)的處理煤篙。比如一些網(wǎng)站過(guò)了一定的時(shí)間不進(jìn)行操作斟览,就會(huì)退出登錄讓你重新登陸頁(yè)面,當(dāng)然這不用攔截器你或許也可以完成這功能辑奈,但是會(huì)很麻煩而且代碼會(huì)產(chǎn)生大量重復(fù)苛茂,所以我們需要用到攔截器
在src目錄下的api目錄創(chuàng)建一個(gè)js文件
import axios from 'axios' //引入axios
//下面這兩個(gè)不一定需要引入,看你項(xiàng)目需要攔截的時(shí)候做什么操作鸠窗,但是一般都需要引入store
import store from '@/store/index' //引入store
import router from '@/router' //引入router
創(chuàng)建一個(gè)axios實(shí)例
let instance = axios.create({
headers: {
'content-type': 'application/x-www-form-urlencoded'
}
})
編寫請(qǐng)求攔截器
這個(gè)攔截器會(huì)在你發(fā)送請(qǐng)求之前運(yùn)行
我的這個(gè)請(qǐng)求攔截器的功能是為我每一次請(qǐng)求去判斷是否有token妓羊,如果token存在則在請(qǐng)求頭加上這個(gè)token。后臺(tái)會(huì)判斷我這個(gè)token是否過(guò)期稍计。
// http request 攔截器
instance.interceptors.request.use(
config => {
const token = sessionStorage.getItem('token')
if (token ) { // 判斷是否存在token躁绸,如果存在的話,則每個(gè)http header都加上token
config.headers.authorization = token //請(qǐng)求頭加上token
}
return config
},
err => {
return Promise.reject(err)
})
響應(yīng)攔截器
// http response 攔截器
instance.interceptors.response.use(
response => {
//攔截響應(yīng)臣嚣,做統(tǒng)一處理
if (response.data.code) {
switch (response.data.code) {
case 1002:
store.state.isLogin = false
router.replace({
path: 'login',
query: {
redirect: router.currentRoute.fullPath
}
})
}
}
return response
},
//接口錯(cuò)誤狀態(tài)處理净刮,也就是說(shuō)無(wú)響應(yīng)時(shí)的處理
error => {
return Promise.reject(error.response.status) // 返回接口返回的錯(cuò)誤信息
})
最后把實(shí)例導(dǎo)出就行了
export default instance
在需要的頁(yè)面導(dǎo)入就可以使用了
import instance from './axios'
/* 驗(yàn)證登陸 */
export function handleLogin (data) {
return instance.post('/ds/user/login', data)
}