You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

拥有跨域授权时,如何通过AJAX为其他域名设置Cookie?

跨域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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 02:55:21