最近在項(xiàng)目開發(fā)中,遇到下面這樣一個問題:
在進(jìn)行敏感操作之前颜骤,每個請求需要攜帶token,但是token 有有效期,token 失效后需要換取新的token并繼續(xù)請求。
需求分析:
每個請求都需要攜帶 token 厢洞,所以我們可以使用 axios request 攔截器,在這里典奉,我們給每個請求都加 token,這樣就可以節(jié)省每個請求再一次次的復(fù)制粘貼代碼躺翻。
token 失效問題,當(dāng)我們token 失效卫玖,我們服務(wù)端會返回一個特定的錯誤表示公你,比如 token invalid,但是我們不能在每個請求之后去做刷新 token 的操作呀假瞬,所以這里我們就用 axios response 攔截器陕靠,我們統(tǒng)一處理所有請求成功之后響應(yīng)過來的數(shù)據(jù),然后對特殊數(shù)據(jù)進(jìn)行處理脱茉,其他的正常分發(fā)剪芥。
功能實(shí)現(xiàn)
分析完問題后,我們來實(shí)現(xiàn)功能
安裝axios :npm i axios
在 main.js 注冊 axios
jsVue.use(Vuex)
Vue.use(VueAxios, axios)
Vue.use(qs)
注:qs琴许,使用axios粗俱,必須得安裝 qs,所有的Post 請求,我們都需要 qs,對參數(shù)進(jìn)行序列化寸认。
在 request 攔截器實(shí)現(xiàn)
axios.interceptors.request.use(
config => {
config.baseURL = '/api/'
config.withCredentials = true // 允許攜帶token ,這個是解決跨域產(chǎn)生的相關(guān)問題
config.timeout = 6000
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 攔截器實(shí)現(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)
}
)
http://www.reibang.com/p/ff8541e0976a