【发布时间】:2016-11-12 12:46:36
【问题描述】:
即使我在 Angular 的 $http 服务中分配了标头,我仍然遇到此错误:
function Hello($scope, $http) {
$http({
method: 'GET',
url: 'http://localhost:8080/races',
headers: {
'Access-Control-Allow-Headers': 'accept',
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Origin': '*'
},
}).then(function successCallback(response) {
$scope.races = response;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
这是控制台上的完整错误消息:
XMLHttpRequest cannot load http://localhost:8080/races. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63343' is therefore not allowed access. The response had HTTP status code 403.
HTML:
<!doctype html>
<html ng-app>
<head>
<title>Hello AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="hello.js"></script>
</head>
<body>
<div ng-controller="Hello">
<p>The ID is {{races.raceId}}</p>
<p>The name is {{races.raceName}}</p>
</div>
</body>
</html>
当我打开 localhost:8080/races 时,我可以完全看到 json:
[{"raceId":8446,"raceName":"test1"},{"raceId":8447,"raceName":"test2"}]
【问题讨论】:
-
您没有在请求中设置它......它必须在服务器上设置以作为响应。您无法通过请求控制它
标签: javascript angularjs http-headers xmlhttprequest