这里说的js跨域是指通过js在不同的域之间进行数据传输或通信,比如用ajax向一个不同的域请求数据,或者通过js获取页面中不同域的框架中(iframe)的数据。只要协议、域名、端口有任何一个不同,都被当作是不同的域。
//添加商品到购物车 $scope.addToCart=function(){ $http.get('http://localhost:9107/cart/addGoodsToCartList.doitemId=' + $scope.sku.id +'&num='+$scope.num).success( function(response){ if(response.success){ location.href='http://localhost:9107/cart.html';//跳转到购物车页面 }else{ alert(response.message); } } ); }
XMLHttpRequestcannot load http://localhost:9107/cart/addGoodsToCartList.doitemId=112344&num=1. No'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://localhost:9100' is therefore not allowed access. The responsehad HTTP status code 400.
3、跨域解决方案CORS
response.setHeader("Access-Control-Allow-Origin", "http://localhost:9105"); response.setHeader("Access-Control-Allow-Credentials", "true");
Access-Control-Allow-Origin是HTML5中定义的一种解决资源跨域的策略。
它是通过服务器端返回带有Access-Control-Allow-Origin标识的Response header,用来解决资源的跨域权限问题。
使用方法,在response添加 Access-Control-Allow-Origin,例如
Access-Control-Allow-Origin:www.google.com |
//添加商品到购物车 $scope.addToCart=function(){ $http.get('http://localhost:9107/cart/addGoodsToCartList.doitemId=' + $scope.sku.id +'&num='+$scope.num,{'withCredentials':true}).success( function(response){ ....... } ); }
@CrossOrigin(origins="http://localhost:9105",allowCredentials="true")