CORS实现(JS)跨域请求

1、在被请求方(8080)添加消息头

  /key :Access-Control-Allow-Origin   value:向该方法请求跨域的地址(可以写成*,表示允许所有的url访问该方法)

response.setHeader("Access-Control-Allow-Origin", "http://localhost:8081/");

  如果涉及到cookie的操作,还需要加上另外一个头信息,如果value为true则表示允许跨域cookie的操作,如果上面的地址是*,则无法实现跨域cookie的操作

response.setHeader("Access-Control-Allow-Credentials", "true");

  或者使用SpringMVC的注解,注意只支持jdk1.8以上版本

//origins:里面可以填写多个访问地址 allowCredentials默认是true,可以省略不写
@CrossOrigin(origins= {"http://localhost:8081/"},allowCredentials="true")

2、在JS请求端(8081)添加信息

  {'withCredentials':true}

$scope.addToCart=function(){
    $http.get('http://localhost:8080/cart/addGoodsToCartList.do?itemId='
    + $scope.sku.id +'&num='+$scope.num,{'withCredentials':true}).success(
            function(response){
                .......                 
            }                
    );        
}

 

  至此就可以实现跨域请求的操作

猜你喜欢

转载自www.cnblogs.com/709539062rao/p/12944504.html
今日推荐