会话管理中的 Cookie以及在浏览器和 Express 中操作 Cookie:
🍪 一、Cookie 在会话管理中的作用
✅ Cookie 的定义:
Cookie 是服务器发送到浏览器并保存在本地的小段文本数据,浏览器会在之后的请求中将这些数据回传给服务器。
✅ Cookie 的作用:
- 维持会话(如:登录状态、购物车)
- 记录用户信息(如:主题设置、语言偏好)
- 跟踪用户行为(如:访问记录、广告推荐)
🧠 二、Cookie 的特点
特性 | 说明 |
---|---|
大小限制 | 单个 Cookie 大小最多约 4KB |
数量限制 | 每个域名下最多 20~50 个 |
自动发送 | 浏览器自动将同源 Cookie 携带到请求头中 |
安全性较低 | 可被拦截/篡改,敏感信息应避免存 Cookie 中 |
支持设置属性 | expires 、max-age 、httpOnly 、secure 、sameSite 等 |
🌐 三、浏览器操作 Cookie(前端)
✅ 1. 读取 Cookie:
console.log(document.cookie); // "username=admin; token=xxx"
✅ 2. 设置 Cookie:
document.cookie = "username=admin";
document.cookie = "theme=dark; max-age=3600"; // 1小时有效
✅ 3. 删除 Cookie:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
⚠️ 删除 Cookie 的关键在于设置过期时间为过去。
🚀 四、在 Express 中操作 Cookie
Express 默认不支持 Cookie,需要中间件 cookie-parser
npm install cookie-parser
✅ 1. 初始化中间件
const express = require('express');
const cookieParser = require('cookie-parser');const app = express();
app.use(cookieParser());
✅ 2. 设置 Cookie
app.get('/set', (req, res) => {res.cookie('username', 'admin', {maxAge: 1000 * 60 * 60, // 1小时httpOnly: true, // 前端无法通过 JS 访问});res.send('Cookie set!');
});
✅ 3. 读取 Cookie
app.get('/get', (req, res) => {const username = req.cookies.username;res.send(`Username is ${username}`);
});
✅ 4. 删除 Cookie
app.get('/delete', (req, res) => {res.clearCookie('username');res.send('Cookie deleted!');
});
🔒 五、常见 Cookie 属性说明
属性 | 作用 |
---|---|
maxAge | 设置 Cookie 存活时间(毫秒) |
expires | 设置过期时间(Date 类型) |
httpOnly | 只允许服务器访问,防止 XSS 攻击 |
secure | 只在 HTTPS 下传输 |
sameSite | 防止 CSRF,可设为 Strict 、Lax 、None |
path | 设置 Cookie 生效路径 |
domain | 设置 Cookie 作用域 |
✅ 六、总结:Cookie vs Session 区别(简表)
特性 | Cookie | Session |
---|---|---|
存储位置 | 客户端 | 服务器端 |
安全性 | 较低,容易被窃取 | 较高,存储在服务器上 |
大小限制 | 有限制(4KB) | 无明显限制 |
保持状态 | 客户端持久化 | 服务端维护 |
生命周期 | 可控(Expires / max-age) | 一般依赖服务器超时设置 |