必须同时满足前端 credentials: 'include'、服务端 Access-Control-Allow-Credentials: true 且 Access-Control-Allow-Origin 为具体源(不能为 *),三者缺一不可;因浏览器强制限制,携带凭证时 Origin 不得通配,否则静默丢弃响应。

必须同时满足前端设置 credentials: 'include'、服务端响应头包含 Access-Control-Allow-Credentials: true,且 Access-Control-Allow-Origin 不能为 *——三者缺一不可,否则浏览器直接拒绝读取响应。
为什么 Access-Control-Allow-Origin: * 和 Access-Control-Allow-Credentials: true 不能共存
这是浏览器硬性限制,不是服务端配置错误。当请求携带凭证(cookie、Authorization 头等),浏览器要求源必须精确可识别,防止恶意站点滥用通配符绕过身份隔离。一旦服务端返回 Access-Control-Allow-Origin: *,哪怕同时写了 Access-Control-Allow-Credentials: true,浏览器也会静默丢弃响应体,并报错:
Response to preflight request doesn't pass access control check: 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'.
- 开发阶段常见于本地
file://协议打开 HTML 文件——此时 Origin 是null,无法匹配任何非通配的Origin值,必须用本地服务器(如live-server、python -m http.server)启动前端 - 生产环境需将前端部署域名(如
https://app.example.com)完整写入Access-Control-Allow-Origin,不能只写example.com或带端口的http://localhost:3000(协议和端口必须一致) - 若需支持多个前端源,服务端需动态读取请求头
Origin,白名单校验后原样回写(注意防范反射型 CORS 漏洞)
credentials: 'include' 在不同请求方式中的写法差异
这个选项控制浏览器是否在跨域请求中自动带上目标域的 Cookie,但写法因 API 而异,漏掉或写错就无效:
-
fetch:必须显式传入{ credentials: 'include' },不写默认是'omit' -
XMLHttpRequest:需在open()后、send()前设置xhr.withCredentials = true -
axios:全局配置withCredentials: true,或单次请求加{ withCredentials: true } -
jQuery.ajax:需同时设crossDomain: true和xhrFields: { withCredentials: true }
注意:credentials: 'same-origin' 不适用于跨域场景,它只在同源时生效;'omit' 是默认值,即不带 cookie。
立即学习“前端免费学习笔记(深入)”;
服务端设置 Access-Control-Allow-Credentials 的典型陷阱
这个响应头本身很简单,但常因配套配置缺失导致失败:
- Express 中间件里如果用了
res.header('Access-Control-Allow-Origin', '*'),再加res.header('Access-Control-Allow-Credentials', 'true')也无效——必须先改 Origin 为具体地址 - Nginx 配置中,
add_header默认不继承到预检(OPTIONS)响应,需显式对OPTIONS请求块重复添加,或用always参数:add_header 'Access-Control-Allow-Credentials' 'true' always; - Spring Boot 的
@CrossOrigin注解默认不开启凭证支持,需手动指定:@CrossOrigin(origins = "https://app.example.com", allowCredentials = "true") - Cookie 本身还需额外属性才能跨域传输:服务端 Set-Cookie 响应头必须含
SameSite=None; Secure(HTTPS 环境下),否则浏览器拒绝发送
最容易被忽略的是:即使所有 CORS 头都正确,如果服务端生成的 Cookie 缺少 SameSite=None 和 Secure,或者前端发起的是 HTTP 协议而 Cookie 标了 Secure,整个流程依然会静默失败——这时候 Network 面板里看不到 Cookie 出现在 Request Headers,但控制台可能没报 CORS 错,得逐层检查请求头和响应头。



















