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

本地跨端口场景下,如何让React获取Express设置的Cookie?

解决本地跨端口环境下Cookie无法生效的配置修改方案

1. 调整Cookie的secure属性

本地开发环境一般用HTTP协议,你当前设置的secure: true会要求Cookie仅在HTTPS环境下存储,直接将其改为false即可:

res
  .cookie("access_token", token, {
    httpOnly: true,
    sameSite: "none",
    secure: false, // 本地HTTP环境修改为false,生产HTTPS环境改回true
  })
  .status(200)
  .json(others);

2. 配置Express的CORS中间件

跨端口请求属于跨域场景,必须让后端允许前端携带凭证(Cookie)。先确保安装了cors包,再在Express中添加如下配置:

const cors = require('cors');

app.use(cors({
  origin: 'http://localhost:3000', // 指定允许的前端域名
  credentials: true, // 开启允许携带凭证的权限
}));

注意:origin不能用通配符*,否则credentials: true会失效。

3. 前端请求时开启凭证携带

React发起登录请求时,需要明确设置携带凭证的参数:

  • 用axios的写法:
axios.post('http://localhost:8880/api/login', loginData, {
  withCredentials: true
});
  • 用fetch的写法:
fetch('http://localhost:8880/api/login', {
  method: 'POST',
  credentials: 'include',
  body: JSON.stringify(loginData),
  headers: {
    'Content-Type': 'application/json'
  }
});

额外提醒

sameSite: "none"搭配secure: true是HTTPS生产环境跨域的标准配置,但本地HTTP环境下必须把secure设为false,否则浏览器会拒绝存储Cookie。

内容的提问来源于stack exchange,提问作者Captai-N

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 04:37:03