vue全局路由守卫beforeEach+token验证+node

在后端安装jsonwebtoken         npm i jsonwebtoken --save

在 login.js文件中引入      // 引入jwtconst jwt = require('jsonwebtoken');                  // 定义秘钥    const secretKey = 'itsource'

生成token const token = jwt.sign(accountInfo,secretKey, {expiresIn: 60 * 60})

发送给前端
accountInfo==> 表示被加密的对象

secretKey===>被定义的秘钥

{expiresIn: 60 * 60} token的有效时间  单位是秒
将token发送给前端

 

前端代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
<template>
  <div>
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名" prop="user">
        <el-input v-model.number="ruleForm.user"></el-input>
      </el-form-item>
 
      <el-form-item label="密码" prop="pass">
        <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
      </el-form-item>
 
      <el-form-item label="确认密码" prop="checkPass">
        <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
      </el-form-item>
 
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
 
<script>
// 引入qs
import qs from "qs";
 
export default {
  data() {
    var checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("用户名不能为空"));
      }
 
      //它的意思是 当符合要求的条件的时候,就触发回调函数。这个回调的函数是显示成功的标识
      setTimeout(() => {
        callback();
      }, 500);
    };
 
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
 
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      // 存放用户的数据是 ruleForm  而不是data
      ruleForm: {
        pass: "",
        checkPass: "",
        user: ""
      },
      rules: {
        pass: [{ validator: validatePass, trigger: "blur" }],
 
        checkPass: [{ validator: validatePass2, trigger: "blur" }],
 
        user: [{ validator: checkAge, trigger: "blur" }]
      }
    };
  },
 
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          alert("submit!");
          //获取用户的数据哦
          //console.log(this.ruleForm.user, this.ruleForm.pass )
 
          //用一个对象 username是存放的名字哦  用的是一个爹对象将他们存起来
          let params = {
            username: this.ruleForm.user,
            password: this.ruleForm.pass
          };
          console.log(params);
          // 发送请求 把参数发给后端(把用户名和密码发给后端 验证是否存在这个账号)
          this.axios
            .post("http://127.0.0.1:666/login/checklogin", qs.stringify(params))
            .then(response => {
               // 接收后端返回的数据   token是token username用户名
              let {error_code, reason, token, username} = response.data;
              // 判断
              if (error_code === 0) {
                // 把token存在浏览器的本地存储中
                window.localStorage.setItem('token', token);
                // 把用户名存入本地存储
                window.localStorage.setItem('username', username);
                // 弹成功提示
                this.$message({
                  type: "success",
                  message: reason
                });
                // 跳转到后端首页
                this.$router.push("/");
              } else {
                // 弹失败提示
                this.$message.error(reason);
              }
            })
            .catch(err => { 
              console.log(err);
            });
        } else {
          // 否则就是false
          alert("前端验证失败 不能提交给后端!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
};
</script>
 
<style lang="less" scoped>
.demo-ruleForm {
  width: 30%;
  margin: 40px auto 10px auto;
  min-width: 300px;
}
</style>

  在main.js中

复制代码
// 全局路由守卫 拦截所有路由
router.beforeEach((to, from, next) => {
  // 获取token
  const token = window.localStorage.getItem('token');
  // 有token
  if (token) {
    // 直接放行
    next();
  } else {  // 否则是没有
    // 如果去的是登录页
    if (to.path === '/login') {
      // 直接放行
      next();
    } else {
      // 如果去的是其他页,跳转到登录页
      Message.error('请登录以后再操作!')
      // 跳转到登录页
      return next({ "path": "/login" })
    }
  }
})
复制代码
复制代码
  后盾login.js代码中
const express = require("express"); const router = express.Router(); // 引入连接数据库的模块 const connection = require("./connect"); // 引入jwt const jwt = require('jsonwebtoken'); // 定义秘钥 const secretKey = 'itsource'; // 统一设置响应头 解决跨域问题 router.all("*", (req, res, next) => { // 设置响应头 解决跨域(目前最主流的方式) res.header("Access-Control-Allow-Origin", "*"); next(); }); /* 验证用户名和密码是否正确的路由 */ router.post("/checklogin", (req, res) => { // 接收用户名和密码 let { username, password } = req.body; // 构造sql(查询用户名和密码是否存在) const sqlStr = `select * from account where username='${username}' and password='${password}'`; // 执行sql语句 connection.query(sqlStr, (err, data) => { if (err) throw err; // 判断 if (!data.length) { // 如果不存在 res.send({ error_code: 1, reason: "请检查用户名或密码!" }); } else { // 存在 // 当前登录账号数据 const obj = data[0]; // 转为字符串 const objStr = JSON.stringify(obj); // 生成一个全新对象 const accountInfo = JSON.parse(objStr); // 生成token const token = jwt.sign(accountInfo, secretKey, { expiresIn: 60 * 60 }) res.send({ 'error_code': 0, 'reason': '欢迎您!登录成功!', token, "username": accountInfo.username }) } }); }); module.exports = router;
复制代码

 

posted @   南风晚来晚相识  阅读(1276)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示