先上代碼:
// 給axios配置響應攔截器
axios.interceptors.response.use(
function(response) {
// 當返回狀態碼錶示token值無效時
if (response.data.code === 4002) {
Vue.prototype.$message.error('登錄已過期,請重新登錄')
router.replace('/login')
} else {
// 其他情況
return response.data
}
},
function(error) {
// 對響應錯誤做點什麼
return Promise.reject(error)
}
)
最開始我的想法是在vue的main.js中直接使用this.$routers,但是在網上看了很多例子,實驗無果。
因爲此時的this我打印出來是undefined,所以this.$message和this.$router都不能用。
關於登錄失效的提示,可以使用Vue.prototype.$message,
跳轉的話,可以使用router.replace(’/login’)
值得注意的是,如果你在請求失敗的代碼中寫了this.$message.error(‘錯誤信息’),那麼 return response.data也會返回一個打印的錯誤,此時不會顯示Vue.prototype.$message.error(‘登錄已過期,請重新登錄’),優先顯示請求失敗的代碼中寫了this.$message.error(‘錯誤信息’)
所以要寫if else判斷,當後端返回狀態碼是4002(tooken有誤)時,不返回後端響應的數據,只觸發 Vue.prototype.$message.error(‘登錄已過期,請重新登錄’)和router.replace(’/login’)即可。
而其他情況的時候,直接返回後端相應的數據即可。