内容
了解 session、cookie
用 node 服务器实现 session、cookie
前端实战演示
1. cookie与session
cookie:浏览器在电脑硬盘中开辟的一块空间,主要供服务器端存储数据。
- cookie中的数据是以域名的形式进行区分的。
- cookie中的数据是有过期时间的,超过时间数据会被浏览器自动删除。
- cookie中的数据会随着请求被自动发送到服务器端。
session:实际上就是一个对象,存储在服务器端的内存中,在session对象中也可以存储多条数据,每一条数据都有一个sessionid做为唯一标识。
验证图解:
2. node服务器实现
在node.js中需要借助express-session实现session功能。,传送门:express-session
中间件内部具体操作
为请求对象添加session 属性,session的值为对象,session可在用户登录成功后保存用户信息,方法内部会在我们向session 对象中存储数据时生成 sessionId,为当前存储数据的唯一标识,然后将sessionId 存储在客户端的 cookie 中。当客户端再次访问服务器时,方法会拿到客户端传来的 cookie ,并从中提取 sessionId,并根据sessionId 从 cookie 中找到用户信息。此时身份验证成功!
搭建node 服务器代码 略(详情可参考:node服务器搭建)
2.1 首先在入口文件(app.js)写入创建session 的中间件
app.use(session({
//创建session中间件
secret: 'secret keys',
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 24 * 60 * 60 * 1000 // session过期时间
}
}))
2.2 在登录成功,以及退出登录时都要对session 进行操作
const express = require('express');
const router = express.Router();
const dbConfig = require('../util/dbconfig.js'); // 数据库连接池
router.post('/login', async(req, res) => {
const {
username, password } = req.body;
let sql = 'select password from test where username=?';
let sqlArr = [username];
let result = await dbConfig.sysqlConnect(sql, sqlArr);
if (result.length) {
if (password === result[0].password) {
req.session.username = username // 为请求对象添加用户信息
res.send({
status: 200,
msg: '登录成功'
})
} else {
res.send({
status: 400,
msg: '用户名或密码错误'
})
}
} else {
res.send({
status: 400,
msg: '用户名不存在'
})
}
})
// 退出登录
router.get('/loginout', (req, res) => {
req.session.destroy(err => {
if (err == null) {
res.clearCookie('connect.sid'); // 删除客户端对应的cookie,(注意这里的值怒唯一,根据客户端的属性名而定)
res.send({
msg: '退出登录', status: 200 })
} else {
res.send({
msg: '退出失败', status: 400 })
}
})
})
// 判断用户是否登录
router.get('/loginStatus', (req, res) => {
if (req.session && req.session.username) {
//若果session中存在信息
res.send('var isLogin = true')
} else {
res.send('var isLogin = false')
}
})
module.exports = router
注意:此处的数据库连接池可参考:mysql连接
3. 实战演示
3.1 验证效果展示
3.2 步骤
①:在服务器上创建静态页面:login.html 、index.html
②:用 ajax 请求 访问相应接口
③:在需要的页面请求用户状态接口,确保用户处于登录状态
- login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="./js/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<form id="loginForm">
<input type="text" name="username" id="">
<input type="password" name="password" id="">
<input type="submit" value="登录">
</form>
<script>
$(function() {
$('#loginForm').on('submit', function() {
const formdata = $(this).serialize();
$.ajax({
url: '/users/login',
type: 'post',
data: formdata,
success(res) {
if (res.status == 200) {
location.href = '/index.html'
} else {
alert('用户名或密码错误')
}
}
})
return false
})
})
</script>
</body>
</html>
index.html
<!-- 判断登录状态 -->
<script src="/users/loginStatus"></script>
<script>
if (!isLogin) location.href = '/login.html'
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="./js/jquery.min.js"></script>
<title>Document</title>
<style>
a {
text-decoration: none;
font-size: 30px;
color: hotpink;
}
</style>
</head>
<body>
<h1>welcome to index</h1>
<a href="javascript:;">退出登录</a>
<script>
$('a').on('click', function() {
$.ajax({
url: '/users/loginout',
success(res) {
if (res.status == 200) {
console.log('退出登录');
location.href = '/login.html'
}
}
})
})
</script>
</body>
</html>
注意:在需要的页面添加状态判断,确保用户身份