Node.js Express中如何从服务端向客户端设置Cookie?
一、先修复服务端的语法错误
你的服务端代码存在两处语法错误,这会直接导致代码无法正常执行:
res.cookie的配置对象末尾缺少闭合的}if语句块在res.send后没有闭合}
二、处理跨域Cookie传递问题
如果你的客户端页面和服务端不在同一域名/端口下(比如客户端运行在http://localhost:8080,服务端在https://localhost:443),必须做以下两处修改:
服务端配置CORS允许凭证
如果使用cors中间件,需要开启凭证支持并指定允许的客户端来源:
const cors = require('cors'); // 替换成你实际的客户端域名/端口 app.use(cors({ origin: 'http://localhost:8080', credentials: true }));
客户端fetch请求添加credentials选项
浏览器默认不会在跨域请求中保存服务端发送的Cookie,必须在fetch中加上credentials: 'include':
const response = await fetch("https://localhost:443/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data), credentials: 'include' // 新增该行,允许携带Cookie });
三、修复安全问题
用用户密码作为JWT密钥非常不安全,应该使用固定的安全密钥(建议从环境变量读取,避免硬编码),同时不要把密码等敏感信息放进JWT的payload里:
// 推荐用dotenv管理环境变量,这里先写示例值 const secretKey = process.env.JWT_SECRET || 'your_secure_fixed_secret_key'; // 只在JWT中存储必要的用户标识,比如用户名 let accessToken = jwt.sign({ acc_name: data.acc_name }, secretKey, { expiresIn: '1h' });
四、修正后的完整代码
服务端代码
const authenticateUser = (req, res) => { let data = req.body; // 假设users是你的用户数据源(比如数据库查询结果) if (data.acc_name === users.acc_name && data.password === users.password) { const secretKey = process.env.JWT_SECRET || 'your_secure_fixed_secret_key'; let accessToken = jwt.sign({ acc_name: data.acc_name }, secretKey, { expiresIn: '1h' }); res.cookie('token', accessToken, { maxAge: 3600000, httpOnly: true, secure: true, // HTTPS环境建议开启,确保Cookie仅通过HTTPS传输 sameSite: 'Lax' // 防范CSRF攻击,根据需求调整为Strict/None }); res.send({ 'notice': 'Success' }); } else { res.status(401).send('Thông tin đăng nhập không hợp lệ.'); } }; app.post('/login', authenticateUser);
客户端代码
<script> document.getElementById('loginForm').addEventListener('submit', async function (e) { e.preventDefault(); let data = { acc_name: document.getElementById("acc_name").value, password: document.getElementById("password").value }; try { const response = await fetch("https://localhost:443/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data), credentials: 'include' }); if (response.ok) { const responseData = await response.json(); document.getElementById("result").textContent = responseData.notice; } else { document.getElementById("result").textContent = "Invalid."; } } catch (error) { console.error("Error: ", error); } }); </script>
内容的提问来源于stack exchange,提问作者Mạnh Dương
相关产品推荐
相关产品推荐

