
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;
发表评论
最新留言
第一次来,支持一个
[***.219.124.196]2025年04月26日 03时45分06秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
mybtis-plus 出现 Wrong namespace
2019-03-15
升级java11后,maven命令打包报错
2019-03-16
springboot redis key乱码
2019-03-16
Win10禁用自带的笔记本键盘
2019-03-16
insmod模块的几种常见错误
2019-03-16
写时复制集合 —— CopyOnWriteArrayList
2019-03-16
什么是redis的缓存雪崩, 穿透, 击穿?
2019-03-16
【转载】DSP基础--定点小数运算
2019-03-16
idea thymeleaf页面变量报错解决
2019-03-16
云游戏,打响5G第一战
2019-03-16
Docker 拉取镜像速度太慢
2019-03-16
【毕设-STM32f103寄存器版本】智能防盗系统
2019-03-16
勒索病毒Kraken2.0.7分析
2019-03-16
MySQL错误1366处理方法
2019-03-16
VxWorks 操作系统学习笔记
2019-03-16
驱动程序之_1_字符设备_13_USB设备_1_基本概念
2019-03-16
微机原理 6-计算机中常用的数制
2019-03-16
window系统下安装使用curl命令工具
2019-03-16
假如计算机是中国人发明的,那代码应该这么写
2019-03-16