1.对于不同源之间的访问存在跨域,a.huhu.com访问a.haha.com提示跨域出错。
例子:a.huhu.com访问a.haha.com(注意域名的区别)
解决方案一:a.huhu.com设置反向代理,如果是nginx的话,可以配置如果,将请求转发到a.haha.com即可
location /test {
proxy_pass http://a.haha.com
}
解决方案二: a.haha.com设置允许跨域访问,php代码示例
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Origin: ' . $allow_domain); //设置允许该域名访问
header('Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, If-Modified-Since');
其中$allow_domain=a.huhu.com
2.扩展。同源域名下的访问但是application没有
例子:a.huhu.com访问b.huhu.com,这种情况访问没有提示跨域问题,而且在setcookie的时候,response显示cookie正常设置,但是application下的cookie没有
解决方案:
1)服务端要设置允许跨域访问
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Origin: ' . $allow_domain); //设置允许该域名访问
header('Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, If-Modified-Since');
其中$allow_domain=a.huhu.com,Access-Control-Allow-Credentials=true的情况下,Access-Control-Allow-Origin不能为*
2)客户端请求设置,要带上xhrFields: {withCredentials: true},并且请求的方法必须要是POST(别问我为什么要POST,踩的坑多了就知道了)
$.ajax({
url: url,
data: params,
type: type,
xhrFields: {withCredentials: true},
success: function(res) {
cb(res)
},
error: function() {
cb({});
}
})