阿杰,我给你整理一下 withCredentials 属性详解,这是前端(尤其是 AJAX / Fetch / Axios)中与跨域请求相关的重要属性。


一、概念

  • 作用:指示浏览器在 跨域请求 时是否应该发送 凭据(credentials)
    • 凭据包括:
      1. Cookies
      2. HTTP 认证信息(Basic Auth、Bearer Token)
      3. TLS 客户端证书
  • 默认值false(跨域请求不会带 cookies 或认证信息)

二、适用场景

  1. AJAX / XHR
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/data', true);
xhr.withCredentials = true; // 发送 cookie
xhr.send();

  1. Fetch API
fetch('https://example.com/data', {
    method: 'GET',
    credentials: 'include' // 同 withCredentials = true
})
.then(res => res.json())
.then(data => console.log(data));

  1. Axios
axios.get('https://example.com/data', { withCredentials: true })
     .then(res => console.log(res.data));


三、属性值说明

说明
true发送请求时包含凭据(cookies / HTTP 认证)
false不发送凭据(默认)

四、跨域注意事项(CORS)

withCredentials = true 时,跨域请求需要满足 CORS 相关配置

  1. 服务端响应头必须包含
Access-Control-Allow-Origin: https://yourdomain.com  // 不能使用 '*'
Access-Control-Allow-Credentials: true

  1. 请求头不能使用通配符
    • Access-Control-Allow-Origin 不能是 *
    • 必须明确指定源域
  2. 预检请求
    • 对于带 withCredentials 的 POST、PUT、DELETE 请求,浏览器会先发送 OPTIONS 预检请求

五、示例

1. XMLHttpRequest 带 cookie

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/userinfo', true);
xhr.withCredentials = true;
xhr.onload = function () {
    console.log(xhr.responseText);
};
xhr.send();

2. Fetch 带 cookie

fetch('https://api.example.com/userinfo', {
    credentials: 'include'
})
.then(res => res.json())
.then(data => console.log(data));

3. Axios 跨域请求

axios.defaults.withCredentials = true;

axios.get('https://api.example.com/userinfo')
     .then(res => console.log(res.data));


六、总结

  • 核心作用:是否随请求发送 cookies / 凭据
  • 前端设置
    • XMLHttpRequest.withCredentials = true
    • Fetch APIcredentials: 'include'
    • AxioswithCredentials: true
  • 服务端配合:CORS 响应头必须允许凭据
  • 常见问题
    1. 设置了 withCredentials = true 但服务端没有 Access-Control-Allow-Credentials: true → 跨域失败
    2. Access-Control-Allow-Origin* 时,凭据无法发送