最近在項目中要用到攔截器,坦白說是第一次聽說這玩意,所以資料查了好久,現(xiàn)在也算是明白了攔截器的作用。我的理解就是攔截每一次你的請求和響應(yīng),然后進行相應(yīng)的處理。比如一些網(wǎng)站過了一定的時間不進行操作,就會退出登錄讓你重新登陸頁面,當(dāng)然這不用攔截器你或許也可以完成這功能,但是會很麻煩而且代碼會產(chǎn)生大量重復(fù),所以我們需要用到攔截器
在src目錄下的api目錄創(chuàng)建一個js文件
import axios from 'axios' //引入axios
//下面這兩個不一定需要引入,看你項目需要攔截的時候做什么操作,但是一般都需要引入store
import store from '@/store/index' //引入store
import router from '@/router' //引入router
創(chuàng)建一個axios實例
let instance = axios.create({
headers: {
'content-type': 'application/x-www-form-urlencoded'
}
})
編寫請求攔截器
這個攔截器會在你發(fā)送請求之前運行
我的這個請求攔截器的功能是為我每一次請求去判斷是否有token,如果token存在則在請求頭加上這個token。后臺會判斷我這個token是否過期。
// http request 攔截器
instance.interceptors.request.use(
config => {
const token = sessionStorage.getItem('token')
if (token ) { // 判斷是否存在token,如果存在的話,則每個http header都加上token
config.headers.authorization = token //請求頭加上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
},
//接口錯誤狀態(tài)處理,也就是說無響應(yīng)時的處理
error => {
return Promise.reject(error.response.status) // 返回接口返回的錯誤信息
})
最后把實例導(dǎo)出就行了
export default instance
在需要的頁面導(dǎo)入就可以使用了
import instance from './axios'
/* 驗證登陸 */
export function handleLogin (data) {
return instance.post('/ds/user/login', data)
}