跨域问题,前端主动向后台发送cookie
跨域是什么?
从一个域名的网页访问另一个域名的资源,就会出现跨域。只要协议、端口、域名有一个不同就会出现跨域
例如:
1.协议不同 http://www.baidu.com:80 和 https://www.baidu.com:80
2.端口不同 https://www.badu.com:80 和 https://www.baidu.com:8888
3.域名不同 https://www.jd.com:80 和 https://www.taobao.com:80
当浏览器向后台发起请求时,如果是跨域请求,那么就不会发送cookie给后台,而cookie中有一些信息,例如JsessionID等身份信息就不能发送给后台,这样会导致服务器认为你没有登录。
而如果前台已经解决了主动发送cookie的问题,后台如果header中没有“Access-Control-Allow-Origin”,并且值为*或者浏览器当前访问网页的域名时,那么会直接进入ajax的error方法中,浏览器会直接将返回的内容丢掉。
解决方案:
- 前端:
- jquery ajax
2.angular.js$.ajax({
url: '自己要请求的url',
method:'请求方式', //GET POST PUT DELETE
xhrFields:{withCredentials:true},
success:function(data){
//自定义请求成功做什么
},
error:function(){
//自定义请求失败做什么
}
})
$http.get(url, {withCredentials: true});
$http.post(url,data, {withCredentials: true});
- 后台:PHP
header('Access-Control-Allow-Credentials:true');
header('Access-Control-Allow-Origin:http://localhost:8080');
注意,这里http://localhost:8080 不能设置为 * 来允许全部,如果在 Credentials 是true 的情况下。因为浏览器会报错如下:
A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin http://localhost:8080' is therefore not allowed access
所以要设置成客户端页面的 域名。
php支持多个地址跨域访问
//跨域访问的时候才会存在此字段
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
$allow_origin = array(
'http://www.a.com',
'http://www.b.com'
);
if(in_array($origin, $allow_origin)){
header('Access-Control-Allow-Origin:'.$origin);
header('Access-Control-Allow-Methods:POST');
header('Access-Control-Allow-Headers:x-requested-with,content-type');
}