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发送给前端

 

前端代码






  在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;

 

转载于:https://www.cnblogs.com/IwishIcould/p/10962213.html

你可能感兴趣的:(vue全局路由守卫beforeEach+token验证+node)