拥有跨域授权时,如何通过AJAX为其他域名设置Cookie?
可以通过foo.com的AJAX请求为bar.com设置Cookie,但必须同时满足以下全部条件:
1. 服务器端(bar.com)配置要求
- 响应头必须包含
Access-Control-Allow-Credentials: true,允许请求携带凭证(包括Cookie) Access-Control-Allow-Origin不能使用通配符*,必须明确指定为请求源的完整地址,比如https://foo.com(需和请求的协议、域名完全一致)
2. 前端AJAX请求配置要求
发起请求时必须开启凭证携带:
- 使用Fetch API时,需设置
credentials: 'include':fetch('https://bar.com/api/set-cookie', { method: 'POST', credentials: 'include', // 其他请求参数(如请求体、headers等) }); - 使用XMLHttpRequest时,需设置
withCredentials = true:const xhr = new XMLHttpRequest(); xhr.open('POST', 'https://bar.com/api/set-cookie'); xhr.withCredentials = true; xhr.send();
3. Cookie本身的属性要求
bar.com在返回的Set-Cookie头中设置的Cookie,需满足:
Domain属性需指定为bar.com或.bar.com(确保Cookie归属目标域名)- 若站点使用HTTPS,需添加
Secure属性,保证Cookie仅通过HTTPS传输 SameSite属性不能设为Strict,可选择Lax或None(设为None时必须搭配Secure属性)
只要有任一条件不满足,跨域AJAX请求都无法成功为bar.com设置Cookie。
内容的提问来源于stack exchange,提问作者Romalex
相关产品推荐
相关产品推荐

