1. 无关Cookie跨域Ajax请求
客户端
以 Jquery 的 ajax 为例:
$.ajax({
url:'http://10.153.43.66/antopic/anZaiAuth',
type:'post',
async:false,
data:{'username':username,'password':password,'anzai_userid':anzai_userid},
crossDomain: true,
xhrFields: {
withCredentials: true // 携带跨域cookie
},
success:function (data) {
alert('1111');die;
data1 = data;
console.log(data);
},
error(err) {
console.log('出错');
console.log(err);
}
});
主要注意的是参数 crossDomain: true。发送Ajax时,Request header 中会包含跨域的额外信息,但不会含cookie。
服务器:
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: http://:8080");
header("Access-Control-Allow-Methods:POST,GET");
header("Access-Control-Allow-Headers:x-requested-with,content-type");
header("Content-type:text/json;charset=utf-8");
说明:header("Access-Control-Allow-Origin: http://:8080"); 允许访问的网站, * 为所有网站都可访问。
若header("Access-Control-Allow-Credentials: true"),
则header("Access-Control-Allow-Origin: http://:8080");不能设置为*
对应客户端的 xhrFields.withCredentials: true
参数,服务器端通过在响应 header 中设置 Access-Control-Allow-Credentials = true
来运行客户端携带证书式访问。通过对 Credentials 参数的设置,就可以保持跨域 Ajax 时的 Cookie。这里需要注意的是:
服务器端 Access-Control-Allow-Credentials = true
时,参数Access-Control-Allow-Origin
的值不能为 '*'
。
通过设置 withCredentials: true
,发送Ajax时,Request header中便会带上 Cookie 信息。