必须同时满足前端配置、后端响应头和Cookie自身属性三方面要求:前端需设withCredentials: true或credentials: 'include';后端需返回Access-Control-Allow-Origin(非*)和Access-Control-Allow-Credentials: true;Cookie须含SameSite=None、Secure及正确Domain。

在跨域 API 请求中,仅设置 credentials: 'include' 不足以让 Cookie 被携带,必须同时满足前端配置、后端响应头和 Cookie 自身属性三方面要求。缺一不可。
前端 fetch 或 axios 需显式启用 credentials
使用 fetch 时,必须手动指定 credentials: 'include'(默认是 'omit'):
fetch('https://api.example.com/data', {
method: 'GET',
credentials: 'include' // ✅ 关键:显式声明
})
使用 axios 时,需在请求配置中设置 withCredentials: true:
axios.get('https://api.example.com/data', {
withCredentials: true // ✅ 等价于 credentials: 'include'
})
注意:credentials: 'same-origin' 在跨域时不生效;'include' 是唯一可跨域传 Cookie 的选项。
立即学习“Java免费学习笔记(深入)”;
后端必须返回正确的 CORS 响应头
服务端响应中必须包含以下两个关键头,且不能为通配符 *:
-
Access-Control-Allow-Origin:必须指定明确的源(如https://your-app.com),不能是*(否则浏览器会拒绝携带 Cookie) -
Access-Control-Allow-Credentials:必须设为true
例如 Node.js/Express 中的正确写法:
res.header('Access-Control-Allow-Origin', 'https://your-app.com');
res.header('Access-Control-Allow-Credentials', 'true');
Cookie 必须满足安全属性要求
浏览器只会在满足条件时才在跨域请求中发送 Cookie,需确保服务端设置 Cookie 时包含:
-
SameSite=None:允许跨站上下文发送(注意:必须搭配Secure) -
Secure:强制 Cookie 只通过 HTTPS 传输(开发时若用localhost,现代浏览器允许 HTTP + localhost 绕过此限制,但生产环境必须 HTTPS) -
Domain 属性合理:若 API 域名为
api.example.com,前端在app.example.com,则 Cookie 的Domain应设为.example.com(开头带点,表示子域名共享)
示例 Set-Cookie 响应头:
Set-Cookie: sessionId=abc123; Path=/; Domain=.example.com; Secure; HttpOnly; SameSite=None
常见失败原因速查
- 前端漏写
credentials: 'include'或withCredentials: true - 后端
Access-Control-Allow-Origin设成了* - 后端没返回
Access-Control-Allow-Credentials: true - Cookie 缺少
SameSite=None或未配Secure(尤其在 HTTPS 环境下) - Cookie 的
Domain写错(比如写成api.example.com而非.example.com) - 浏览器隐私策略拦截(如 Safari ITP、Chrome 第三方 Cookie 限制,需用户交互触发或满足 Storage Access API 条件)


















