fetch 请求携带 cookie 需设 credentials: 'include',跨域时后端须返回 access-control-allow-credentials: true 且 access-control-allow-origin 指定具体源,并确保 cookie 含 samesite=none; secure(跨域)或 samesite=lax/strict(同域)。

要在 Fetch 请求中携带 Cookie 和凭证,关键在于设置 credentials 选项。默认情况下,Fetch 不会发送 Cookie,即使用户已登录,服务端也收不到认证信息。
必须设置 credentials: 'include'
这是最常用且明确的方式,表示始终带上 Cookie(包括跨域和同域请求):
-
credentials: 'include'—— 请求头自动包含Cookie,响应头需有Access-Control-Allow-Credentials: true(跨域时必需) -
credentials: 'same-origin'—— 仅同域请求带 Cookie(默认值,但显式写出更清晰) -
credentials: 'omit'—— 完全不发 Cookie(等价于未设置)
后端必须配合跨域凭证支持
若请求跨域(如前端 http://localhost:3000 调用 https://api.example.com),服务端响应头必须包含:
Access-Control-Allow-Credentials: true-
Access-Control-Allow-Origin不能为*,必须指定具体源(如http://localhost:3000)
否则浏览器会直接拒绝响应,控制台报错:"The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'"。
确保 Cookie 本身可被 JavaScript 发送
服务端设 Cookie 时,需满足以下任一条件,浏览器才会在 Fetch 中自动带上它:
-
SameSite=None; Secure(跨域必需,且必须走 HTTPS) -
SameSite=Lax或SameSite=Strict(同域或部分导航场景下有效) - 未设置
SameSite(旧行为,现代浏览器默认按Lax处理) - Cookie 的
Domain和Path需匹配当前请求地址
完整示例
发起一个带登录态的跨域 GET 请求:
fetch('https://api.example.com/profile', {
method: 'GET',
credentials: 'include', // ? 关键
headers: {
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(data => console.log(data));
注意:无需手动读写 document.cookie,浏览器自动管理;也不用在 headers 中手动加 Cookie 字段——那是无效且被忽略的。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











