作为接口框架,会经常遇到需要跨域的问题,有些需要共享session的接口会因为ajax提交了不同的cookies而导致无法获取到sessid的问题,记录一下解决方法:
phalapi:
//允许所有跨域,同时兼容Credentials,这里也可以使用单独的域名
\PhalApi\DI()->response->addHeaders('Access-Control-Allow-Origin', $_SERVER['HTTP_ORIGIN']);
//允许客户端携带cookie,解决跨域共享session
\PhalApi\DI()->response->addHeaders('Access-Control-Allow-Credentials', "true");
JavaScript:
加入:
xhrFields:{
withCredentials:true
},
最终效果:
$.ajax({
url: 'http://*******',
type: 'POST',
async:true,
xhrFields:{
withCredentials:true
},
data: {
username:userName,
password:pwd
},
success: function(respon){
console.log(respon);
var res=eval(respon);
},
error: function(){
alert('服务器发生错误!');
}
});
设置 withCredentials 为 true 的请求中会包含 A 端的所有Cookie,这些Cookie仍然遵循同源策略,所以,你只能访问其中和 B 端同根域的Cookie,而无法访问其他域Cookie。
总结一下就是:
要想跨域,你得有后台(需要服务器端配合)。
PC:Firefox,发现你和Chrome的表现不一致的情况还真不多。Firefox中不要在同步模式(async:false)下传递Cookie