Ajax跨域请求中的Cookie问题(默认不带cookie等凭证)

1.原生Ajax请求方式,设置跨域请求附带详细参数

var xhr = new XMLHttpRequest();
xhr.open("POST", "http://xxxx.com/demo/b/index.php", true);
xhr.withCredentials = true; //支持跨域发送cookies
xhr.send();

 

2.Jquery的Ajax请求,设置跨域附带详细参数

$.ajax({
    url: apiUrl.getCookie('getone'),
    data: { age: 11 },
    xhrFields: {
        withCredentials:true  //支持附带详细信息
    },
    crossDomain:true,//请求偏向外域
    success: function (data) {
        alert(data);
    }
});

 

3.服务端支持

header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: http://www.xxx.com");

或者webconfig中修改配置:

  <configuration>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="http://www.xxx.com" />
        <add name="Access-Control-Allow-Methods" value="GET, POST" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
  </configuration>

 

能够成功使用带有 Cookie 的资源请求需要满足以下几个条件

  • XMLHttpRequest 对象中指定了 withCredentials = true

  • 服务器响应头中 Access-Control-Allow-Credentials: true

  • 服务器响应头中 Access-Control-Allow-Origin 不能为 *

 

其他资料:http://segmentfault.com/a/1190000003693381?_ea=330169

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

posted @ 2016-01-22 10:37  天马3798  阅读(6222)  评论(0编辑  收藏  举报