You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MERN栈认证系统Node后端设置的Cookie React前端浏览器无法读取问题

问题排查与修复方案

1. 前端axios请求配置缺失

跨域场景下浏览器默认不会主动携带Cookie,你当前的请求未开启携带凭证的配置,同时登录请求也需要添加相同配置,否则后端返回的Set-Cookie响应头会被浏览器拦截,不会本地存储。
修复方法:

  • 单个请求添加配置:
const res = await axios.post(
  "http://localhost:5000/api/user/refresh_token",
  null,
  { withCredentials: true } // 新增该行配置
);
  • 也可以全局配置axios,避免每个请求重复添加:
axios.defaults.withCredentials = true;

注意:登录接口的axios请求也必须添加该配置

2. 后端CORS配置错误

当前你直接使用app.use(cors())的默认配置,既没有开启跨域凭证支持,也没有明确允许前端源地址,浏览器会拦截跨域带Cookie的请求。
修复方法,替换原有CORS配置:

app.use(cors({
  origin: "http://localhost:3000", // 替换为你React前端实际的访问地址
  credentials: true // 允许跨域请求携带凭证
}));

注意:origin不能设置为*,否则会和credentials配置冲突,必须明确填写前端的源地址

3. 可选补充:Cookie属性适配

本地开发使用localhost不同端口的场景,可以给Cookie添加sameSite配置避免浏览器安全策略拦截:

res.cookie("refreshtoken", refresh_token, {
  httpOnly: true,
  path: "/api/user/refresh_token",
  maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days
  sameSite: "lax", // 本地开发、前后端同站场景适用,跨站生产环境需要改为sameSite: 'none'同时开启secure: true
  // 生产环境HTTPS部署时需要添加 secure: true
});

内容的提问来源于stack exchange,提问作者emerald_91

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 08:24:02