Fetch API 中 credentials 参数的作用是什么?

fetch API 中的 credentials 参数用于控制凭证发送行为,默认为 'omit'。它有三种取值:omit、same-origin 和 include,分别适用于不同的请求场景。

网络协议 中等 fetch 网络 Fetch API

在 JavaScript 的 fetch API 中,credentials 属性用于控制在网络请求中是否发送用户凭证(例如 cookies、HTTP authentication headers 或 TLS client certificates)。这些凭证用于认证和安全目的,特别是在涉及跨域资源的请求时。

credentials 属性支持三个可选值:

  • omit:这是默认行为,表示请求不发送任何凭证信息。适用于公开资源请求或不需要身份验证的场景。
    fetch('https://example.com/data', {
      method: 'GET',
      credentials: 'omit' // 默认,不携带凭证
    });
    
  • same-origin:只在请求目标为同域(same-origin)时发送凭证。适用于需要认证但仅局限于当前域名的请求。
    fetch('https://example.com/data', {
      method: 'GET',
      credentials: 'same-origin' // 同域时才携带凭证
    });
    
  • include:无论在什么情况下(包括跨域请求)都发送凭证。适用于需要认证的跨域 API 调用,但要求服务器配置 Access-Control-Allow-Credentials: true
    fetch('https://api.example.com', {
      method: 'GET',
      credentials: 'include' // 总是携带凭证
    });
    

当使用跨域请求(如 credentials: 'include'),浏览器会自动检查服务器响应头:

  • 响应中必须设置 Access-Control-Allow-Origin 明确指定源域(不能是通配符 *)。
  • 如果凭证发送被接受,响应会被允许处理;否则,promise 可能无法正确解析到返回的数据。