token過期自動跳轉(zhuǎn)到登錄頁面
設(shè)置token有效期為2小時,超過兩小時 token失效 ,接口返回結(jié)果:{code:0,msg:'token過期',}
每次路由跳轉(zhuǎn)都會對token進(jìn)行判斷,設(shè)置一個全局的beforeEach鉤子函數(shù)福也,如果token存在就跳到你所需要的頁面,否則直接跳轉(zhuǎn)到登錄頁面,讓用戶重新存取token
全局路由鉤子:router.beforeEach
router.beforeEach(async (to, from, next) => {
? ? ? ? ? ? //獲取token
? ? ? ? ? ? const hasToken = getToken()
? ? ? ? ? ? if (hasToken) {
? ? ? ? ? ? ? ? //token存在欲鹏,如果當(dāng)前跳轉(zhuǎn)的路由是登錄界面
? ? ? ? ? ? ? ? if (to.path === '/login') {
? ? ? ? ? ? ? ? ? ? // if is logged in, redirect to the home page
? ? ? ? ? ? ? ? ? ? next({
? ? ? ? ? ? ? ? ? ? ? ? path: '/'
? ? ? ? ? ? ? ? ? ? })
? ? ? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? ? ? //在這里,就拉去用戶權(quán)限臭墨,判斷用戶是否有權(quán)限訪問這個路由
? ? ? ? ? ? ? ? } catch (error) {
? ? ? ? ? ? ? ? ? ? // remove token and go to login page to re-login
? ? ? ? ? ? ? ? ? ? await store.dispatch('user/resetToken')
? ? ? ? ? ? ? ? ? ? Message.error(error || 'Has Error')
? ? ? ? ? ? ? ? ? ? next(`/login?redirect=${to.path}`)
? ? ? ? ? ? ? ? }
? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? //token不存在
? ? ? ? ? ? ? ? if (whiteList.indexOf(to.path) !== -1) {
? ? ? ? ? ? ? ? ? ? //如果要跳轉(zhuǎn)的路由在白名單里赔嚎,則跳轉(zhuǎn)過去
? ? ? ? ? ? ? ? ? ? next()
? ? ? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? ? ? //否則跳轉(zhuǎn)到登錄頁面
? ? ? ? ? ? ? ? ? ? next(`/login?redirect=${to.path}`)
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? })
請求攔截 設(shè)置
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
const service = axios.create({
? baseURL: process.env.VUE_APP_BASE_API,
? timeout: 5000
})
//發(fā)送請求時把token攜帶過去
service.interceptors.request.use(
? config => {
? ? if (store.getters.token) {
? ? ? config.headers['sg-token'] = getToken()
? ? }
? ? return config
? },
? error => {
? ? console.log(error)
? ? return Promise.reject(error)
? }
)
//請求響應(yīng)
service.interceptors.response.use(
? response => {
? ? console.log(response.data)
? ? const res = response.data
? ? // token過期,重返登錄界面
? ? if (res.code === 0) {
? ? ? store.dispatch('user/logout').then(() => {
? ? ? ? location.reload(true)
? ? ? })
? ? }
? ? return res
? },
? error => {
? ? Message({
? ? ? message: error.msg,
? ? ? type: 'error',
? ? ? duration: 5 * 1000
? ? })
? ? return Promise.reject(error)
? }
)
export default service