最近搞一個vue的項目,接口帶了權限驗證,于是乎稍微研究了一下,中間遇到的各種坑都來源于自己概念的不熟悉。
主要呢是分兩步:
一是vue路由層的控制,由于項目的路由有規律可循,所以沒有采用網上requireAuth那種在需要加驗證的路由上配置meta(具體見:http://www.49028c.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' })//跳轉到登錄頁 } } else { next(); }})
二是http 攔截器 ,統一處理所有http請求和響應,就得用上 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失效的參數 sessionStorage.setItem("user_token",'') sessionStorage.setItem("LoginUser",'{}') alert(response.data.msg); window.location.href='/#/login'//需求方要求一旦出錯立即跳轉登錄,所以采取這種侵入式的手段。 }else{ return response }}, function (error) { return Promise.reject(error);});
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答