跨域是什么?

从一个域名的网页访问另一个域名的资源,就会出现跨域。只要协议、端口、域名有一个不同就会出现跨域
例如:
1.协议不同 http://www.baidu.com:80https://www.baidu.com:80
2.端口不同 https://www.badu.com:80https://www.baidu.com:8888
3.域名不同 https://www.jd.com:80https://www.taobao.com:80
当浏览器向后台发起请求时,如果是跨域请求,那么就不会发送cookie给后台,而cookie中有一些信息,例如JsessionID等身份信息就不能发送给后台,这样会导致服务器认为你没有登录。
而如果前台已经解决了主动发送cookie的问题,后台如果header中没有“Access-Control-Allow-Origin”,并且值为*或者浏览器当前访问网页的域名时,那么会直接进入ajax的error方法中,浏览器会直接将返回的内容丢掉。

解决方案:

  • 前端:
  1. jquery ajax
    1. $.ajax({
    2. url: '自己要请求的url',
    3. method:'请求方式', //GET POST PUT DELETE
    4. xhrFields:{withCredentials:true},
    5. success:function(data){
    6. //自定义请求成功做什么
    7. },
    8. error:function(){
    9. //自定义请求失败做什么
    10. }
    11. })
    2.angular.js
    1. $http.get(url, {withCredentials: true});
    2. $http.post(url,data, {withCredentials: true});
  • 后台:PHP
    1. header('Access-Control-Allow-Credentials:true');
    2. header('Access-Control-Allow-Origin:http://localhost:8080');
    3. 注意,这里http://localhost:8080 不能设置为 * 来允许全部,如果在 Credentials 是true 的情况下。因为浏览器会报错如下:
    4. 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
    5. 所以要设置成客户端页面的 域名。
    6. php支持多个地址跨域访问
    7. //跨域访问的时候才会存在此字段
    8. $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
    9. $allow_origin = array(
    10. 'http://www.a.com',
    11. 'http://www.b.com'
    12. );
    13. if(in_array($origin, $allow_origin)){
    14. header('Access-Control-Allow-Origin:'.$origin);
    15. header('Access-Control-Allow-Methods:POST');
    16. header('Access-Control-Allow-Headers:x-requested-with,content-type');
    17. }