credentials 选项控制 fetch 请求是否携带凭证:omit(默认,不发送)、same-origin(仅同源发送)、include(始终发送);跨域时需后端配合 access-control-allow-credentials: true 且 access-control-allow-origin 不为 *。

在 JavaScript Fetch API 中,credentials 选项用于控制请求是否携带用户凭证(如 Cookie、HTTP 认证信息、TLS 客户端证书)。它直接影响跨域请求时的身份认证行为,用错会导致 401 错误或 Cookie 不发送。
credentials 的三个可选值及含义
omit(默认):不发送任何凭证,即使当前页面已登录、Cookie 存在,请求也不会带上 Cookie 或授权头。
same-origin:仅当请求 URL 与当前页面同源(协议 + 域名 + 端口完全一致)时才发送凭证;跨域请求自动忽略凭证。
include:无论同源还是跨域,都强制携带凭证(Cookie、Authorization 头等)。
常见使用场景与写法
登录后调用受保护的 API 接口(尤其是跨域后端)时,必须显式设置 credentials: 'include':
- 前端域名:
https://app.example.com - API 域名:
https://api.example.com - 需确保后端响应中包含
Access-Control-Allow-Credentials: true,否则浏览器会拒绝响应 - 同时后端的
Access-Control-Allow-Origin不能为*,必须指定确切源(如https://app.example.com)
示例:
fetch('https://api.example.com/profile', {
method: 'GET',
credentials: 'include' // 关键:带上 Cookie
});
同源请求下 credentials 的实际影响
即使同源,credentials 仍起作用:
-
credentials: 'omit'→ 不发 Cookie,适合匿名请求(如首页公开数据) -
credentials: 'same-origin'→ 默认行为,但显式写出更清晰,尤其团队协作时 -
credentials: 'include'→ 同源下也会发 Cookie,和'same-origin'效果一致,但语义更强(强调“需要身份”)
容易踩坑的细节
- 忘记配后端 CORS 头(
Access-Control-Allow-Credentials: true)会导致 fetch 报错:“The value of the 'Access-Control-Allow-Origin' header must not be the wildcard '*' when the request's credentials mode is 'include'” - 开发环境本地启服务(如
localhost:3000)调用后端(localhost:8000)属于跨域,也需配 credentials 和 CORS - 使用
credentials: 'include'时,若用户未登录,浏览器仍会发送空 Cookie,后端需妥善处理未认证状态
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











