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发送给前端
前端代码
<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;
vue全局路由守卫beforeEach+token验证+node的更多相关文章
- vue全局路由守卫beforeEach
在main.js里使用方法 router.beforeEach((to,from,next)=>{}) to,是将要跳转的路由, from,是离开的路由 next是个方法,判断to.path 或 ...
- vue路由守卫用于登录验证权限拦截
vue路由守卫用于登录验证权限拦截 vue路由守卫 - 全局(router.beforeEach((to, from, next) =>来判断登录和路由跳转状态) 主要方法: to:进入到哪个路 ...
- Vue router 全局路由守卫
记录一下全局路由守卫的使用: 方法一:定义一个数组用于检测与管理需要登录的页面,全局路由守卫配合本地存储判断是否跳转 import Vue from 'vue' import Router from ...
- vue2.0 实现导航守卫(路由守卫)---登录验证
路由跳转前做一些验证,比如登录验证,是网站中的普遍需求. 对此,vue-route 提供的 beforeRouteUpdate 可以方便地实现导航守卫(navigation-guards). 导航守卫 ...
- Vue Router 路由守卫:完整的导航解析流程
完整的导航解析流程 1 导航被触发. 2 在失活的组件里调用离开守卫. 3 调用全局的 beforeEach 守卫. 4 在重用的组件里调用 beforeRouteUpdate 守卫 (2.2+). ...
- Vue Router路由守卫妙用:异步获取数据成功后再进行路由跳转并传递数据,失败则不进行跳转
问题引入 试想这样一个业务场景: 在用户输入数据,点击提交按钮后,这时发起了ajax请求,如果请求成功, 则跳转到详情页面并展示详情数据,失败则不跳转到详情页面,只是在当前页面给出错误消息. 难点所在 ...
- vue组件路由守卫钩子函数(beforeRouteEnter、beforeRouteUpdate、beforeRouteLeave)
用法:与mounted,created等同级并列. export default { data() { return { } }, methods: { go() { this.$router.pus ...
- Vue | 路由守卫面试常考
前言 最近在整理基础,欢迎掘友们一起交流学习 结尾有彩蛋哦! Vue Router 路由守卫 导图目录 路由守卫分类 全局路由守卫 单个路由守卫 组件路由守卫 路由守卫执行的完整过程 路由守卫分类 全 ...
- vue --- 全局守卫
vue2.0 实现导航守卫(路由守卫) 路由跳转前做一些验证,比如登录验证,是网站中的普遍需求. 对此,vue-route 提供的 beforeRouteUpdate 可以方便地实现导航守卫(navi ...
随机推荐
- poj 1979 Red and Black 题解《挑战程序设计竞赛》
地址 http://poj.org/problem?id=1979 Description There is a rectangular room, covered with square tiles ...
- WPF DataGrid 绑定数据及时更新的处理
原文:WPF DataGrid 绑定数据及时更新的处理 默认情况下datagrid 绑定数据源后,在界面编辑某一列后,数据不会及时更新到内存对象中.如在同一行上有一个命令对来获取 当前选中行(内存对象 ...
- Codeforces Round #598 (Div. 3) F. Equalizing Two Strings 构造
F. Equalizing Two Strings You are given two strings s and t both of length n and both consisting of ...
- SpringBoot实现登陆
1.依赖 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http:/ ...
- swoole进程间如何通信
Swoole进程间通信的方式 管道pipe 管道用于进程之间的数据交互,Linux系统本身提供了pipe函数用于创建一个半双工通信管道.半双工的通信方式中数据只能单向流动(一端只读一端只写),只能在具 ...
- 打印对象(__str__()和__repr__())
当打印一个类的实例时,返回的字符串是对象的地址信息,如<__main__.Student object at 0x109afb310>,很不好看 可通过在类内定义__str__(),这样打 ...
- 相关pycharm(进阶?)
记录今日发现 对于pycharm细节 注意:项目的位置可以自己定 这里的新建project,建议对python.exe 文件的选择使用自己安装的位置,如下图 create,你就有了一个解释器是你自己安 ...
- SpringMVC跟Struts2的区别
SpringMVC跟Struts2的区别 1.SpringMVC的入口是servlet:Struts2的入口是Filter. 2.SpringMVC性能方面会比Struts2好一点,SpringMVC ...
- 数据库——SQL-SERVER练习(6) 数据库安全性
一.实验准备 (1)运行SQL-SERVER服务管理器, 启动服务(2)运行查询分析器, 以DBA身份登录数据库服务器: 用户名sa, 密码123456(3)打开CREATE-TABLE ...
- Newtonsoft.Json 序列化踩坑之 IEnumerable
Newtonsoft.Json 序列化踩坑之 IEnumerable Intro Newtonsoft.Json 是 .NET 下最受欢迎 JSON 操作库,使用起来也是非常方便,有时候也可能会不小心 ...