推荐答案
// www.javascriptcn.com code example
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
// 使用 cookie-parser 中间件
app.use(cookieParser());
app.get('/', (req, res) => {
// 设置一个名为 'username' 的 Cookie
res.cookie('username', 'john_doe', { maxAge: 900000, httpOnly: true });
// 读取名为 'username' 的 Cookie
const username = req.cookies.username;
res.send(`Hello, ${username || 'Guest'}`);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});本题详细解读
1. 引入 cookie-parser 中间件
cookie-parser 是一个 Express 中间件,用于解析客户端发送的 Cookie 数据。首先需要通过 npm install cookie-parser 安装该中间件,然后在代码中引入并使用它。
const cookieParser = require('cookie-parser');
app.use(cookieParser());2. 设置 Cookie
在 Express 中,可以通过 res.cookie(name, value, [options]) 方法来设置 Cookie。name 是 Cookie 的名称,value 是 Cookie 的值,options 是一个可选参数,用于配置 Cookie 的属性,如 maxAge(过期时间)、httpOnly(是否仅限 HTTP 访问)等。
res.cookie('username', 'john_doe', { maxAge: 900000, httpOnly: true });3. 读取 Cookie
通过 req.cookies 对象可以访问客户端发送的所有 Cookie。req.cookies 是一个键值对对象,键是 Cookie 的名称,值是 Cookie 的值。
const username = req.cookies.username;
4. 删除 Cookie
要删除一个 Cookie,可以使用 res.clearCookie(name) 方法。该方法会将指定名称的 Cookie 设置为过期状态,从而使其被浏览器删除。
res.clearCookie('username');5. Cookie 的安全性
在设置 Cookie 时,建议使用 httpOnly 和 secure 选项来增强安全性。httpOnly 选项可以防止客户端 JavaScript 访问该 Cookie,而 secure 选项则确保 Cookie 仅通过 HTTPS 传输。
res.cookie('username', 'john_doe', { httpOnly: true, secure: true });通过以上步骤,你可以在 Express 应用中有效地处理 Cookie。