必须显式设置 credentials: 'include'(fetch)或 xhr.withcredentials = true(xmlhttprequest),且服务端需返回 access-control-allow-credentials: true 和指定源的 access-control-allow-origin,cookie 还须设 samesite=none; secure。

在 JavaScript 中使用 Ajax(如 fetch 或 XMLHttpRequest)发起跨域请求时,若需携带 Cookie(例如用于登录态鉴权),必须显式设置 withCredentials 为 true,同时服务端也需配合设置响应头 Access-Control-Allow-Credentials: true。否则浏览器会主动忽略 Cookie,且 CORS 预检或主请求会失败。
fetch 请求中启用 withCredentials
fetch 默认不发送 Cookie,需在 options 中指定 credentials 选项:
-
credentials: 'include':始终携带 Cookie(即使同域也发,推荐用于需要鉴权的场景) -
credentials: 'same-origin':仅同域时携带(默认值,跨域时不发) -
credentials: 'omit':从不携带(显式禁用)
示例:
method: 'GET',
credentials: 'include' // 关键:允许携带 Cookie
})
XMLHttpRequest 中设置 withCredentials
在调用 send() 前,必须将 withCredentials 属性设为 true(注意:只能在 open() 之后、send() 之前设置):
xhr.open('GET', 'https://api.example.com/data');
xhr.withCredentials = true; // 关键:启用凭证传输
xhr.onload = () => { console.log(xhr.responseText); };
xhr.send();
服务端必须配合的响应头
仅前端设置不够。当 credentials: 'include' 或 xhr.withCredentials = true 时,服务端响应中必须包含:
Access-Control-Allow-Credentials: true-
Access-Control-Allow-Origin不能为*,必须指定具体源(如https://your-app.com)
例如 Node.js + Express 中:
res.header('Access-Control-Allow-Origin', 'https://your-app.com');res.header('Access-Control-Allow-Credentials', 'true');
常见问题与注意事项
- Cookie 必须标记为
SameSite=None; Secure才能在跨域请求中被携带(HTTPS 环境下) - 本地开发时,
http://localhost:3000和http://localhost:8000视为不同源,仍属跨域 - 如果后端未返回正确的 CORS 凭证头,浏览器控制台会报错:
Failed to fetch或Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is not set - 预检请求(OPTIONS)也需返回上述两个响应头,否则预检失败,主请求不会发出
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











