目录
[✅ Session 原理简要说明](#✅ Session 原理简要说明)
[🧩 示例项目 - 使用 Node.js + Express 实现简单 Session 登录](#🧩 示例项目 - 使用 Node.js + Express 实现简单 Session 登录)
[📁 文件结构](#📁 文件结构)
[🔹 server.js (JavaScript)](#🔹 server.js (JavaScript))
[🔸 index.html (HTML)](#🔸 index.html (HTML))
[▶️ 程序运行步骤](#▶️ 程序运行步骤)
[✅ 程序运行效果](#✅ 程序运行效果)
[🎯 总结](#🎯 总结)
在 Web 应用中,我们经常需要"记住"用户,比如登录状态。这种"记住"就是会话管理(Session)。
✅ Session 原理简要说明
-
Session 是服务器端的机制,用来保存用户的数据(比如用户名、权限等)。
-
每个 Session 会绑定一个唯一的 Session ID。
-
服务器会把这个 Session ID 发送给客户端(浏览器),一般通过 Cookie 存储。
-
浏览器下次请求时会自动带上这个 Session ID,服务器就能识别出这个用户了。
🧩 示例项目 - 使用 Node.js + Express 实现简单 Session 登录
我们来写一个简单的登录系统,登录成功后记住用户信息,通过 Session 实现。
📁 文件结构
javascript
session-demo/
│
├── server.js ← Node.js 主程序 (JavaScript)
└── index.html ← 客户端页面 (HTML)
🔹 server.js (JavaScript)
javascript
// server.js
const express = require('express');
const session = require('express-session');
const path = require('path');
const app = express();
// 设置 session 中间件
app.use(session({
secret: 'keyboard cat', // 用于加密 Session ID 的字符串
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 } // Session 有效时间:1分钟
}));
app.use(express.urlencoded({ extended: true }));
app.use(express.static(__dirname));
// 登录接口
app.post('/login', (req, res) => {
const { username, password } = req.body;
if (username === 'admin' && password === '123456') {
req.session.user = username;
res.send('登录成功!欢迎你,' + username);
} else {
res.send('用户名或密码错误');
}
});
// 访问首页时检查是否已登录
app.get('/welcome', (req, res) => {
if (req.session.user) {
res.send('你已登录,欢迎回来,' + req.session.user);
} else {
res.send('你还没有登录,请先登录');
}
});
// 退出登录
app.get('/logout', (req, res) => {
req.session.destroy();
res.send('你已退出登录');
});
// 启动服务器
app.listen(3000, () => {
console.log('服务器已启动:http://localhost:3000');
});
🔸 index.html (HTML)
html
<!-- index.html -->
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Session 登录示例</title>
</head>
<body>
<h2>登录页面</h2>
<form method="POST" action="/login">
用户名:<input type="text" name="username" /><br>
密码:<input type="password" name="password" /><br>
<button type="submit">登录</button>
</form>
<br>
<a href="/welcome">查看登录状态</a><br>
<a href="/logout">退出登录</a>
</body>
</html>
▶️ 程序运行步骤
- 安装依赖:
javascript
npm install express express-session
- 启动服务器:
javascript
node server.js
- 打开浏览器访问:
javascript
http://localhost:3000
✅ 程序运行效果
-
打开页面,输入
admin
/123456
登录。 -
登录后服务器会设置 Session。
-
点击「查看登录状态」会显示欢迎信息。
-
点击「退出登录」后,Session 会被销毁,再次访问就会提示未登录。
🎯 总结
这个例子通过 express-session
管理 Session,帮助你理解:
-
如何保存登录状态
-
Session 是服务器存储用户信息,客户端只保存一个标识(Session ID)