Token expires and logs out to the login page.

Table of contents

Frontend settings: 

method one:

      1. On the login page, after calling the login interface, directly obtain the current time and save it locally, similar to saving a token.

       2. Obtain the timestamp stored on the local machine in the routing guard, add 15 minutes and compare it with the current time. If it is greater than the current time, the token is invalid and jump directly to the login page.

Method Two:

       1. Directly use the navigation guard to determine whether the token still exists. If not, jump to the login page.


Frontend settings: 
method one:
1. On the login page, after calling the login interface, directly obtain the current time and save it locally, similar to saving a token.

 Code:

// 点击登录
    login(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.$API.Login(this.form).then((res) => {
            // console.log(res, "11111111111");
            if (res.data.code === 200) {
              this.$message({
                message: "登录成功啦",
                type: "success",
                showClose: true,
              });
              // 将登录名使用vuex传递到Home页面
              this.$store.commit("handleUserInfo", res.data.data);
              // 加入 token
              localStorage.setItem("token", res.data.data.token);
              // 添加时间戳
               //待写
              // 跳转到首页
              // console.log(1111111);
              this.$router.replace("/index");
            }
          });
        } else {
          //lu 新加
          this.$message({
            message: "登录失败,请重新登录",
            type: "error",
            showClose: true,
          });
          return false;
        }
      });
    },
2. Obtain the timestamp stored on the local machine in the routing guard, add 15 minutes and compare it with the current time. If it is greater than the current time, the token is invalid and jump directly to the login page.

 ps:

1. The reason for adding 15 minutes is because the back-end setting of my project is that the token expires in 20 minutes. This time can be set randomly according to the project.

2. In most projects, token expiration is provided by the backend, and the frontend only needs to judge it at the interception point.

Method Two:
1. Directly use the navigation guard to determine whether the token still exists. If not, jump to the login page.
// 导航守卫
// 使用 router.beforeEach 注册一个全局前置守卫,判断用户是否登陆
router.beforeEach((to, from, next) => {
  if (to.path === "/login") {
    next();
  } else {
    let token = localStorage.getItem("Token");
    if (token === null || token === "" || token === undefined) {
      console.log(token, "进行判断的token");
      next("/login");
    } else {
      document.title = "项目标题";
      next();
    }
  }
});

Guess you like

Origin blog.csdn.net/CMDN123456/article/details/132215999