路由中間件,導航之前驗證auth

1. 需求:每次用戶刷新頁面時,會需要做token校驗,但不刷新頁面就不會進行請求發(fā)送

2. 說明:前后端分離開發(fā),使用redis做用戶信息緩存。token為用戶校驗的負載,考慮如果用戶不刷新頁面,會出現(xiàn)什么,因為localStorage不會過期,考慮Cookie的關(guān)聯(lián)。

3. 代碼:

import router from './router'
import store from './store'
import {Message} from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {getToken} from '@/utils/auth' // get token from localStorage
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({showSpinner: false}) // NProgress Configuration

const whiteList = ['/login'] // 白名單

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()
  // set page title
  document.title = getPageTitle(to.meta.title)
  // determine whether the user has logged in
  const hasToken = getToken();
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page,如果已經(jīng)登陸,還要訪問登陸頁面,則重定向到首頁
      next({path: '/'});
      NProgress.done()
    } else {
      // 在vuex中保存有用戶信息的,直接通過
      const hasGetUserInfo = store.getters.name;
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // 首次保存用戶信息
          await store.dispatch('user/getInfo')
          next()
        } 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}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
});
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 目錄 ·大型網(wǎng)站軟件系統(tǒng)的特點 ·大型網(wǎng)站架構(gòu)演化發(fā)展歷程 ·初始階段的網(wǎng)站架構(gòu) ·需求/解決問題 ·架構(gòu) ·應(yīng)用...
    zhyang0918閱讀 2,837評論 0 16
  • 今天看到一位朋友寫的mysql筆記總結(jié),覺得寫的很詳細很用心,這里轉(zhuǎn)載一下,供大家參考下,也希望大家能關(guān)注他原文地...
    信仰與初衷閱讀 4,833評論 0 30
  • Swift1> Swift和OC的區(qū)別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴謹 對...
    cosWriter閱讀 11,652評論 1 32
  • feisky云計算、虛擬化與Linux技術(shù)筆記posts - 1014, comments - 298, trac...
    不排版閱讀 4,346評論 0 5
  • 昨天所有游記寫完,今天進行照片刪除,忽然記起在杭州拍下的郁金香時和好友討論如何拍出它們的濃郁,熱烈。開始只是拍出了...
    遇見在感恩節(jié)閱讀 269評論 0 3

友情鏈接更多精彩內(nèi)容