錯誤:
Failed to load xxx: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
背景:
在學習AngularJS的$http服務測試demo時出現該錯誤,demo實例:
<div ng-app="myApp" ng-controller="myCtrl"> <h1>服務器相應的信息為:</h1> <p>{{ responseMsg }}</p> </div> <script> var app = angular.module('myApp',[]); app.controller('myCtrl',function($scope,$http){ $http({ method: 'GET', url: 'http://www.flyroc.top:8001/server0project/hello' }).then(function successCallback(response) { $scope.responseMsg = response.data; }, function errorCallback(response) { }); }); </script>
解決:
目前的瀏覽器為了數據的安全,所有請求被嚴格限制在同一域名下,如果需要從不同的服務器(不同域名)上獲取數據,那么需要使用跨域HTTP請求。
實現跨域的方式是在請求的目標網站后台中(以java servlet為例)添加如下代碼:
response.setHeader("Access-Control-Allow-Origin","*"); //允許所有域名訪問
response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
response.setHeader("Access-Control-Allow-Credentials", "true");
親測只用response.setHeader("Access-Control-Allow-Origin","*");可以解決。