美文网首页
路由中间件,导航之前验证auth

路由中间件,导航之前验证auth

作者: 领带衬有黄金 | 来源:发表于2019-10-23 09:40 被阅读0次

    1. 需求:每次用户刷新页面时,会需要做token校验,但不刷新页面就不会进行请求发送

    2. 说明:前后端分离开发,使用redis做用户信息缓存。token为用户校验的负载,考虑如果用户不刷新页面,会出现什么,因为localStorage不会过期,考虑Cookie的关联。

    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,如果已经登陆,还要访问登陆页面,则重定向到首页
          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()
    });
    

    相关文章

      网友评论

          本文标题:路由中间件,导航之前验证auth

          本文链接:https://www.haomeiwen.com/subject/hwehvctx.html