Fastify跨子域Cookie设置失效问题求助
以下是针对你的场景的具体修复步骤:
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时必须保留,否则浏览器会拒绝设置CookiehttpOnly: 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
相关产品推荐
相关产品推荐

