在 JS 中用 fetch 发起携带 Cookie 的请求,必须显式设置 credentials: 'include',且跨域时后端需配置 Access-Control-Allow-Origin 为具体源并返回 Access-Control-Allow-Credentials: true,同时 Cookie 需满足 SameSite、Secure 等属性要求。

在 JS 中用 fetch 发起携带 Cookie 的请求,关键在于显式设置 credentials 选项为 'include'(或 'same-origin'),否则默认不发送 Cookie。
必须设置 credentials 选项
fetch 默认不会发送 Cookie,即使当前域名下存在有效 Cookie。需手动指定:
-
credentials: 'include':始终发送 Cookie(跨域和同源都发) -
credentials: 'same-origin':仅同源请求发送 Cookie(默认值,但显式写出更清晰) -
credentials: 'omit':从不发送 Cookie(等价于不设该字段)
例如发起带 Cookie 的登录后请求:
fetch('/api/user/profile', {
method: 'GET',
credentials: 'include' // ✅ 关键:告诉浏览器带上 Cookie
});后端需配合设置 CORS 响应头
若请求跨域(如前端 http://localhost:3000 调后端 https://api.example.com),光设 credentials: 'include' 不够——浏览器会因安全策略直接拒绝响应,除非后端明确允许:
-
Access-Control-Allow-Origin不能为*,必须指定确切源(如http://localhost:3000) - 必须返回
Access-Control-Allow-Credentials: true
否则控制台会报错:Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.
注意 Cookie 自身的属性限制
即使 fetch 和后端都配置正确,Cookie 仍需满足自身条件才能被自动携带:
-
SameSite属性:若设为Strict或Lax,跨站请求(如从 A 站 iframe 或表单跳转)可能不发送;开发时可临时设为None; Secure(但需搭配 HTTPS) -
Secure属性:仅在 HTTPS 下发送,本地http://localhost不受影响(现代浏览器对 localhost 放宽了 Secure 限制) -
Domain和Path:确保匹配当前请求的域名与路径
常见调试技巧
遇到 Cookie 没发、登录态丢失等问题,可按顺序检查:
- 浏览器开发者工具 → Application → Cookies:确认目标域名下存在预期 Cookie
- Network 面板 → 点击请求 → Headers → Request Headers:查看是否有
Cookie: xxx行 - Network 面板 → 查看响应头:确认含
Access-Control-Allow-Credentials: true(跨域时) - 检查是否触发了预检(OPTIONS)请求,它的响应头也必须包含上述 CORS 头











