最近搞一個vue的項目,接口帶了權(quán)限驗證,于是乎稍微研究了一下,中間遇到的各種坑都來源于自己概念的不熟悉。
主要呢是分兩步:
一是vue路由層的控制,由于項目的路由有規(guī)律可循,所以沒有采用網(wǎng)上requireAuth那種在需要加驗證的路由上配置meta(具體見:https://www.gxlcms.com/article/143928.htm)
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) const router = new Router({...}) router.beforeEach((to, from, next) => { if(/^\/[S|B|V]/.test(to.path)){ if (isLogin()) {//判斷token信息的自寫方法 next(); } else { next({ name: 'login' })//跳轉(zhuǎn)到登錄頁 } } else { next(); } })
二是http 攔截器 ,統(tǒng)一處理所有http請求和響應(yīng),就得用上 axios 的攔截器。
import axios from 'axios' // http request 攔截器 axios.interceptors.request.use(function (config) { config.headers.token = sessionStorage.getItem("user_token")//將接口返回的token信息配置到接口請求中 return config; }, function (error) { return Promise.reject(error); }); // http response 攔截器 axios.interceptors.response.use(function(response){ if(response.data.code=='1001'||response.data.code=='1002'){//具體的判斷token失效的參數(shù) sessionStorage.setItem("user_token",'') sessionStorage.setItem("LoginUser",'{}') alert(response.data.msg); window.location.href='/#/login'//需求方要求一旦出錯立即跳轉(zhuǎn)登錄,所以采取這種侵入式的手段。 }else{ return response } }, function (error) { return Promise.reject(error); });
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com