路由拦截鉴权验证

router.beforeEach((to, from, next) => {
  if(to.path.indexOf("/appPages/")==0){
    if(to.meta.title) {
      document.title = to.meta.title
    }
    closeLayer();
    next();
  }else{
    const token = getCookie('Access-Token');
    // 判断是否有token,有token正常进行导航
    if (!token) {
      // 没有token看看是否由SSO登录中心登录完成,带着ST跳转而来
      const query = formatLocationSearch(window.location.search);
      if (query.ST) {
        // 有st,拿st换老系统token
        post(`${BASE_URL}/uip/login/loginWithSt?st=${query.ST}`).then(res => {

          if (res.resCode === 1) {
            getMenuList(res.data.userDTO.id);
            setCookie('userDTO', escape(JSON.stringify(res.data.userDTO)));
            const token = res.data.tokenInfo.token;
            setCookie('Access-Token', token);
            // 登录成功,获取到菜单后除去遮罩层
            closeLayer();
            next();
          } else {
            window.location.href = `${SSO_CENTER_URl}?from=${window.location.origin}${window.location.pathname}&info=v3`;
          }
        });
      } else {
        //没有st,去登录中心获取st
        window.location.href = `${SSO_CENTER_URl}?from=${window.location.origin}${window.location.pathname}&info=v3`;
      }
    } else {
      next();
    }
  }
});

function getMenuList(userId) {
  get(`${BASE_URL}/uip/smAuthority/queryUserAuthorizedMenuTree?userId=${userId}`).then(res => {
    if (res.resCode === 1) {
      setCookie('menuList', JSON.stringify(res.data));
    }
  })
}

function closeLayer() {
  const preloader = document.querySelector('.preloader');
  preloader.className += ' preloader-hidden-add preloader-hidden-add-active';
  setTimeout(function () {
    preloader.className += ' preloader-hidden';
  }, 750);
}
原文地址:https://www.cnblogs.com/art-poet/p/12845780.html