淺談Vue網(wǎng)絡(luò)請求之interceptors實際應(yīng)用
項目背景
最近在項目開發(fā)中,遇到下面這樣一個問題:
- 在進行銘感操作之前,每個請求需要攜帶token,但是token 有有效期,token 失效后需要換取新的token并繼續(xù)請求。
需求分析
- 每個請求都需要攜帶 token ,所以我們可以使用 axios request 攔截器,在這里,我們給每個請求都加 token,這樣就可以節(jié)省每個請求再一次次的復(fù)制粘貼代碼。
- token 失效問題,當我們token 失效,我們服務(wù)端會返回一個特定的錯誤表示,比如 token invalid,但是我們不能在每個請求之后去做刷新 token 的操作呀,所以這里我們就用 axios response 攔截器,我們統(tǒng)一處理所有請求成功之后響應(yīng)過來的數(shù)據(jù),然后對特殊數(shù)據(jù)進行處理,其他的正常分發(fā)。
功能實現(xiàn)
分析完問題后,我們來實現(xiàn)功能
安裝axios, 這里我們就贅述怎么安裝axios.
在 main.js 注冊 axios
Vue.use(Vuex) Vue.use(VueAxios, axios) Vue.use(qs)
注:qs,使用axios,必須得安裝 qs,所有的Post 請求,我們都需要 qs,對參數(shù)進行序列化。
在 request 攔截器實現(xiàn)
axios.interceptors.request.use(
config => {
config.baseURL = '/api/'
config.withCredentials = true // 允許攜帶token ,這個是解決跨域產(chǎn)生的相關(guān)問題
config.timeout = 2500
let token = sessionStorage.getItem('access_token')
let csrf = store.getters.csrf
if (token) {
config.headers = {
'access-token': token,
'Content-Type': 'application/x-www-form-urlencoded'
}
}
if (config.url === 'refresh') {
config.headers = {
'refresh-token': sessionStorage.getItem('refresh_token'),
'Content-Type': 'application/x-www-form-urlencoded'
}
}
return config
},
error => {
return Promise.reject(error)
}
)
在 response 攔截器實現(xiàn)
axios.interceptors.response.use(
response => {
// 定時刷新access-token
if (!response.data.value && response.data.data.message === 'token invalid') {
// 刷新token
store.dispatch('refresh').then(response => {
sessionStorage.setItem('access_token', response.data)
}).catch(error => {
throw new Error('token刷新' + error)
})
}
return response
},
error => {
return Promise.reject(error)
}
)
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Vue動態(tài)生成el-checkbox點擊無法賦值的解決方法
這篇文章主要給大家介紹了關(guān)于Vue動態(tài)生成el-checkbox點擊無法賦值的解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧2019-02-02
Vue router/Element重復(fù)點擊導(dǎo)航路由報錯問題及解決
這篇文章主要介紹了Vue router/Element重復(fù)點擊導(dǎo)航路由報錯問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07
Vue金融數(shù)字格式化(并保留小數(shù))數(shù)字滾動效果實現(xiàn)
這篇文章主要介紹了Vue金融數(shù)字格式化(并保留小數(shù)) 數(shù)字滾動效果,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04

