vue的token登录检验和路由守卫的配置

发布时间 2023-11-06 17:59:44作者: 小杨同学906

1.登陆操作时,保存token

localStorage.setItem("token",res.data.token)

2.钩子函数

// 钩子函数,访问路由前调用
router.beforeEach((to, from, next) => {
  // 路由需要认证
  if (to.meta.notRequireAuth) {
    next();
  } else {
    if (localStorage.getItem("token")) {
      next();
    } else {
      next({
        path: "login",
        query: { redirect: to.fullPath }
      });
    }
  }
});

* notRequireAuth :将不需要校验的路由 meta 的 notRequireAuth 设置为 true

  meta: {
      notRequireAuth: true
    },

1.axios.js中配置携带token发送请求

axios.interceptors.request.use((config) => {
  // 可以统一设置请求头
  const token = localStorage.getItem("token");
  if (token) {
    config.headers.Token = token;
  }

  // 排除 某种连接
  if (判断条件--不进行拦截) {
    return config; // 直接返回不进行拦截处理
  }
  if (algorithmUrl.includes(config.url)) {
    config.baseURL = window.algorithmImgIp;
  }
  return config;
});