配置 fetch api 的请求凭证模式,需要在调用 fetch() 时传入第二个参数对象,并将 credentials 属性设置为 'include'、'same-origin' 或 'omit'。默认情况下,跨域请求不会发送 cookie,若需携带凭证,必须显式指定为 'include';同源请求则默认发送。

fetch() 在不同源下如何控制 Cookie 发送
当请求目标与当前页面协议、域名或端口不一致时,浏览器会判定为跨域请求。此时若不配置 credentials,Cookie 将被忽略。要强制发送凭证,需将选项设为 'include'。这会导致请求头中包含完整的 Cookie 信息,同时服务器必须配合设置 Access-Control-Allow-Credentials: true 响应头,否则请求会被浏览器拦截。

const url = 'https://api.example.com/data';
// 跨域请求,强制携带 Cookie
fetch(url, {
method: 'GET',
credentials: 'include'
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
上述代码中,credentials: 'include' 确保了即使请求是跨域的,浏览器的 Cookie 存储机制仍会将相关 Cookie 附加到 HTTP 请求头中。这是处理需要身份验证的跨域 API 调用的标准做法。
同源请求中 credentials 的默认行为是什么
对于同源请求(即请求 URL 的协议、主机和端口均与当前页面一致),Fetch API 默认会自动发送 Cookie,无需额外配置。此时 credentials 属性的默认值为 'same-origin'。如果显式设置为 'same-origin',行为与默认一致;若设置为 'omit',则会禁止发送 Cookie,即使请求是同源的。
一个围绕官方 Mailgun JavaScript SDK 构建的 ASE 技能,用于从 Node.js 发送电子邮件和管理 Mailgun API 工作流。它适用于需要事务性消息传递、域名感知电子邮件操作、事件处理以及与 Mailgun 平台直接集成的代理任务。

// 同源请求,默认行为等同于 credentials: 'same-origin'
fetch('/api/user/profile')
.then(response => response.json())
.then(profile => console.log(profile));
// 显式禁止同源请求发送 Cookie
fetch('/api/user/profile', {
credentials: 'omit'
})
.then(response => response.json())
.then(profile => console.log(profile));
在第一个示例中,由于请求路径 /api/user/profile 与当前页面同源,浏览器会自动附带该域名下的 Cookie。第二个示例通过设置 credentials: 'omit',明确告诉浏览器不要发送任何 Cookie,这在某些需要匿名访问的同源接口场景中可能有用。
当服务器未返回正确的 CORS 头时,include 模式会怎样
在使用 credentials: 'include' 进行跨域请求时,如果服务器没有在响应中设置 Access-Control-Allow-Credentials: true,或者错误地设置了 Access-Control-Allow-Origin: *,浏览器将拒绝读取响应内容并抛出网络错误。这是因为安全策略要求:当请求包含凭证时,服务器必须明确授权该特定来源,而不能使用通配符。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!










