最近在項(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
Vue.use(Vuex)
Vue.use(VueAxios, axios)
Vue.use(qs)
注:qs敲霍,俊马。
在 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)
}
)