必须设置 credentials: 'include' 才能携带 cookie,跨域时后端需配置 access-control-allow-origin(非 *)和 access-control-allow-credentials: true,且 cookie 需设 samesite=none; secure。

在 JavaScript 中使用 fetch 发起带 Cookie 的请求,关键在于正确设置 credentials 选项,并确保服务端配合支持跨域 Cookie。
必须设置 credentials: 'include'
默认情况下,fetch 不会携带 Cookie(即使同源)。要发送 Cookie,需显式指定 credentials:
-
'include':始终发送 Cookie(同源或 CORS 场景下都发) -
'same-origin':仅同源时发送(默认值) -
'omit':从不发送 Cookie
常见写法:
```jsfetch('/api/user', {
method: 'GET',
credentials: 'include' // ? 关键
})
```
跨域请求时后端必须允许凭证
如果请求跨域(如前端 http://localhost:3000 调用 https://api.example.com),仅前端设 credentials: 'include' 不够,后端响应头必须包含:
-
Access-Control-Allow-Origin:不能为*,必须是具体源(如http://localhost:3000) Access-Control-Allow-Credentials: true
例如 Node.js + Express 示例:
res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
res.header('Access-Control-Allow-Credentials', 'true');
```
确保 Cookie 本身可被携带
服务端设置的 Cookie 需满足以下任一条件,浏览器才会在 fetch 请求中自动带上:
- 同源请求:Cookie 的
Domain和Path匹配当前页面 - 跨域请求:
SameSite=None且Secure=true(即只在 HTTPS 下生效)
错误示例(现代浏览器会忽略):
```httpSet-Cookie: session=abc123; SameSite=Lax
```
正确跨域 Cookie 示例:
```httpSet-Cookie: session=abc123; SameSite=None; Secure; HttpOnly
```
登录后保持会话的典型流程
完整链路示例:
- 用户登录:POST
/login,后端验证成功后设带SameSite=None; Secure的 Cookie - 后续请求(如获取用户信息):使用
credentials: 'include' - 服务端检查 Cookie 中的 session 并返回数据
代码片段:
```js// 登录
fetch('/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
credentials: 'include'
});
// 获取用户数据(自动携带登录 Cookie)
fetch('/api/profile', { credentials: 'include' })
.then(r => r.json())
.then(data => console.log(data));
```
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











