阿杰,我给你整理一下 withCredentials
属性详解,这是前端(尤其是 AJAX / Fetch / Axios)中与跨域请求相关的重要属性。
一、概念
- 作用:指示浏览器在 跨域请求 时是否应该发送 凭据(credentials)。
- 凭据包括:
- Cookies
- HTTP 认证信息(Basic Auth、Bearer Token)
- TLS 客户端证书
- 凭据包括:
- 默认值:
false
(跨域请求不会带 cookies 或认证信息)
二、适用场景
- AJAX / XHR
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/data', true);
xhr.withCredentials = true; // 发送 cookie
xhr.send();
- Fetch API
fetch('https://example.com/data', {
method: 'GET',
credentials: 'include' // 同 withCredentials = true
})
.then(res => res.json())
.then(data => console.log(data));
- Axios
axios.get('https://example.com/data', { withCredentials: true })
.then(res => console.log(res.data));
三、属性值说明
值 | 说明 |
---|---|
true | 发送请求时包含凭据(cookies / HTTP 认证) |
false | 不发送凭据(默认) |
四、跨域注意事项(CORS)
当 withCredentials = true
时,跨域请求需要满足 CORS 相关配置:
- 服务端响应头必须包含:
Access-Control-Allow-Origin: https://yourdomain.com // 不能使用 '*'
Access-Control-Allow-Credentials: true
- 请求头不能使用通配符
Access-Control-Allow-Origin
不能是*
- 必须明确指定源域
- 预检请求
- 对于带
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 API
:credentials: 'include'
Axios
:withCredentials: true
- 服务端配合:CORS 响应头必须允许凭据
- 常见问题:
- 设置了
withCredentials = true
但服务端没有Access-Control-Allow-Credentials: true
→ 跨域失败 Access-Control-Allow-Origin
为*
时,凭据无法发送
- 设置了
发表回复