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

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

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

 

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

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

 

3.服务端支持ajax

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

或者webconfig中修改配置:segmentfault

  <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 的资源请求须要知足如下几个条件api

  • XMLHttpRequest 对象中指定了 withCredentials = true跨域

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

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

 

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

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

相关文章
相关标签/搜索