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

Fastify跨子域Cookie设置失效问题求助

解决跨域设置Cookie问题(主域→子域Fastify后端)

以下是针对你的场景的具体修复步骤:

1. 修正Fastify的CORS配置

当请求携带凭证(Cookie)时,Access-Control-Allow-Origin不能使用正则表达式,必须返回精确的源地址,同时显式开启凭证支持:

await fastify.register(require('@fastify/cors'), {
  origin: (origin, cb) => {
    // 验证请求源是否属于example.com域
    if (/example\.com$/.test(origin)) {
      cb(null, true);
      return;
    }
    cb(new Error('Not allowed by CORS'));
  },
  methods: ['GET', 'PUT', 'POST', 'DELETE'],
  credentials: true // 关键:允许跨域携带/设置Cookie
});

2. 确保Fetch请求正确配置credentials

跨域场景下必须显式设置credentials: 'include',否则浏览器会忽略响应中的Set-Cookie头:

const requestOptions: RequestInit = {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  redirect: "follow",
  referrerPolicy: "no-referrer",
  credentials: 'include', // 必须添加,跨域时处理Cookie
  body: JSON.stringify({ message })
};

return fetch(`${SERVER_URI}/authenticate`, requestOptions)
  .then(response => response.json())
  .then(result => console.log({ result }));

3. 验证Cookie配置细节

你的Cookie参数基本正确,再确认几个核心点:

  • domain: '.example.com':确保主域example.com和子域api.example.com都能访问该Cookie,设置正确
  • secure: true:站点为HTTPS时必须保留,否则浏览器会拒绝设置Cookie
  • httpOnly: true:这是安全配置,仅限制前端JS读取Cookie,不影响Cookie的正常设置

4. 浏览器端排查验证

打开浏览器开发者工具的Network面板,检查/authenticate请求:

  • 请求头:确认存在Origin: https://example.com
  • 响应头:
    • 确认存在Access-Control-Allow-Origin: https://example.com(精确匹配,不能是正则或通配符)
    • 确认存在Access-Control-Allow-Credentials: true
    • 确认存在完整的Set-Cookie头,格式与后端配置一致

如果以上头信息缺失或不符合要求,浏览器会静默拒绝设置Cookie。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 22:04:59