Express.js中Cookie在浏览器不生效但Postman正常的问题
问题描述
后端通过Express API发送HttpOnly Cookie,使用Postman发起请求时,Set-Cookie头正常显示且Cookie生效;但前端通过Redux发起请求时,浏览器中无法找到该Cookie——响应头中存在Set-Cookie字段,但浏览器并未完成Cookie的存储。已尝试用Moesif插件禁用浏览器CORS,且Express项目已安装配置cors包,问题仍未解决。
相关代码
userController.js
// Public // /users/login GET // auth user const authUser = asyncHandler(async (req, res) => { const { email, password } = req.body; if (!email || !password) { res.status(403); throw new Error("email or password empty"); } const user = await User.findOne({ email }); if (!user) { res.status(404); throw new Error("user not found"); } if (bcrypt.compareSync(password, user.password)) { //generate jwt token and send it genToken(res, user._id); res.status(200).json({ message: "User logged in", user: { id: user._id, name: user.name, email: user.email, }, }); } else { res.status(401); throw new Error("email or password not correct"); } });
genToken.js
const genToken = (res, userId) => { const token = jwt.sign({ userId }, process.env.JWT_SECRET, { expiresIn: "30d", }); // set jwt http cookie on the server res.cookie("jwt", token, { httpOnly: true, secure: false, //////////////// development only sameSite: "strict", maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days, }); };
Redux auth端点
login: builder.mutation({ query: (data) => ({ url: `${USERS_URL}/auth`, // USER_URL=/users method: "POST", body: data, }), }),
server.js
import express from "express"; import cors from "cors"; const app = express(); var corsOptions = { origin: "*", optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204, credentials: true, }; app.use(cors(corsOptions));
问题原因
- CORS配置冲突:当
credentials: true时,CORS的origin不能设为*,浏览器会拒绝这种配置,导致Cookie无法被存储。 - 前端请求未携带凭证:Redux请求默认不会携带跨域凭证(Cookie、HTTP认证等),需要显式配置。
- 注意:HttpOnly Cookie不会出现在
document.cookie中,只能在浏览器开发者工具的「Application」→「Cookies」面板中查看,不要误判为未设置。
解决方案
1. 修改Express的CORS配置
将origin设置为前端实际的域名(比如开发环境通常是http://localhost:3000),不能使用通配符*:
var corsOptions = { origin: "http://localhost:3000", // 替换为你的前端实际访问地址 optionsSuccessStatus: 200, credentials: true, }; app.use(cors(corsOptions));
2. 给Redux请求添加凭证配置
在Redux的mutation中添加credentials: 'include',确保跨域请求携带Cookie:
login: builder.mutation({ query: (data) => ({ url: `${USERS_URL}/auth`, method: "POST", body: data, credentials: 'include', // 关键:携带跨域凭证 }), }),
3. 验证Cookie是否设置成功
打开浏览器开发者工具,切换到「Application」标签页,在左侧菜单找到「Cookies」→ 对应后端域名,查看是否存在名为jwt的Cookie。
内容的提问来源于stack exchange,提问作者Rabah Abellache
相关产品推荐
相关产品推荐

