vue中前端處理token過時的方法與axios請求攔截處理

在處理token過時的這個問題上困擾了我好久,如今終於解決的了,因此分享出來給你們,但願可以對你們有所幫助。前端

首先,固然是路由進行攔截,路由攔截固然是在beforeEach中了:ios

router.beforeEach((to, from, next) => {

iView.LoadingBar.start();
//Util.title(to.meta.title, router.app);
Util.title(to.meta.title);

if (Cookies.get('locking') === '1' && to.name !== 'locking') { // 判斷當前是不是鎖定狀態
next({
replace: true,
name: 'locking'
});
} else if (Cookies.get('locking') === '0' && to.name === 'locking') {
next(false);
} else {


if (!Cookies.get('status') && to.name !== 'login') { // 判斷是否已經登陸且前往的頁面不是登陸頁
//alert('登陸過時!請從新登陸!');

next({
name: 'login'
});
} else if (Cookies.get('status') && to.name === 'login') { // 判斷是否已經登陸且前往的是登陸頁
Util.title();
next({
name: 'home_index'
});
} else {
Util.toDefaultPage(routers, to.name, router, next);
next();
}
}
// })

// }


});

路由攔截事後,固然就到了axios的攔截,在每次的後臺請求中攔截一次判斷後臺token是否過時:ajax

//請求時的攔截
util.ajax.interceptors.request.use(function(config){
    const token = Cookies.get('status');
    if (token) {
        // config.headers.common['Authorization'] = token;
        config.headers.Authorization = token;
    }
    return config
},function(error){
    
    return Promise.reject(error);
});

//響應時的攔截
util.ajax.interceptors.response.use(response => {
    //對響應數據作操做
    if (response.data.msg == '登陸失效') { //這裏是判斷後臺的token是否過時
      
        Cookies.remove("status"); //若是過時則清除前端的token並跳轉到登陸頁
//這裏須要說明一下,若是你是用的是hash模式,使用下面的就能夠了 ,若是使用的是history 模式則使用window.location.href='/login';就能夠了
        window.location.href='#/login';
    }
    return response;
    
},error => {
    //對響應數據錯誤作操做
    debugger
    if(response.data.code == 1000000) {

        Cookies.remove("status");
        window.location.href='#/login'
        
        return Promise.reject(response);
    }
    return Promise.reject(error);
});

axios的攔截我是寫在util.js的文件中的;axios

 

下面是個人公衆號,歡迎你們關注,能夠一塊兒學習一塊兒進步:app

相關文章
相關標籤/搜索