vue全局路由守卫beforeEach+token验证+node
发布日期:2021-05-25 01:14:31 浏览次数:19 分类:博客文章

本文共 2215 字,大约阅读时间需要 7 分钟。

在后端安装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发送给前端

 

前端代码

  在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");// 引入jwtconst 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;

 

上一篇:vue中如何使用echarts,使用axios获取数据
下一篇:vue+elementUI+node实现登录模块--验证用户名是否正确

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2025年04月26日 03时45分06秒