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

跨域请求HTTP头为空,React+Node.js无法设置Cookie求助

React与Node.js跨域场景Cookie及自定义Header无法正常返回问题排查与解决

问题原因

  1. Cookie的secure属性配置错误:本地开发通常使用HTTP协议,而secure: true要求Cookie仅在HTTPS环境下传输,浏览器会直接拒绝接收这类Cookie。
  2. 自定义Header未配置暴露规则:跨域请求中,默认只有Cache-Control、Content-Language等少数安全Header能被前端读取,自定义Header需要通过Access-Control-Expose-Headers明确声明允许暴露,否则前端无法获取。
  3. Cookie的sameSite属性限制:sameSite: "strict"模式下,跨域请求不会携带Cookie,完全阻断了跨域场景下的Cookie传递。

解决方案

服务端代码修改

app.use(morgan("short"));
app.use(express.json());
app.use(cookieParser());

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "http://192.168.43.xxx:5173");
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
  res.setHeader("Access-Control-Allow-Credentials", "true");
  // 添加暴露自定义Header的配置
  res.setHeader("Access-Control-Expose-Headers", "Any-Header");
  next();
});

app.post("/", (req, res) => {
  res.cookie("Access-token", "my very secret token", {
    httpOnly: true,
    maxAge: 1000 * 3600,
    // 本地开发HTTP环境设为false,生产HTTPS环境改为true
    secure: false,
    // 跨域场景调整为lax,若需要第三方域名请求可设为none(需配合secure: true)
    sameSite: "lax",
  });
  res.setHeader("Any-Header", "XXXXXXXXXXXXXXXXXXX");
  res.send({ message: "OK" });
});

客户端代码优化

客户端已正确设置credentials: "include",调整Header读取方式即可获取自定义Header:

const handleSet = async () => {
    var response = await fetch("http://192.168.43.xxx:5000/", {
      method: "POST",
      credentials: "include",
    });

    // 直接获取指定自定义Header
    const customHeader = response.headers.get("Any-Header");
    console.log(customHeader);

    const body = await response.json();
    // 将Headers对象转为普通对象方便查看
    const headersObj = Object.fromEntries(response.headers);
    console.log({ headers: headersObj, body });
    setOutput(JSON.stringify({ headers: headersObj, body }));
};

生产环境注意事项:部署时需将Cookie的secure设为true,同时确保网站使用HTTPS协议;若需要跨第三方域名传递Cookie,可将sameSite设为"none",但必须配合secure: true使用。

内容的提问来源于stack exchange,提问作者Xenon M. Bird

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 19:43:11