我得到 "No 'Access-Control-Allow-Origin' header error " 即使我设置了它

I get "No 'Access-Control-Allow-Origin' header error " even though I set it

即使我在 angular 的 $http 服务中分配了 headers,我仍然遇到此错误:

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"}]

CORS headers需要服务器发送。

The Cross-Origin Resource Sharing standard works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser. Additionally, for HTTP request methods that can cause side-effects on user data (in particular, for HTTP methods other than GET, or for POST usage with certain MIME types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method. Servers can also notify clients whether "credentials" (including Cookies and HTTP Authentication data) should be sent with requests.

Read more.

您的问题与 'Access-Control-Allow-Origin': '*' 需要在服务器上设置有关。通过这样做,您可以启用 CORS(Cross-Origin 资源共享)

浏览器的安全策略会阻止您的 javascript 代码从不在您域内的服务发出请求。例如,如果您的 javascript 代码在 http://example.com and the service you are targeting is found at http://example.com/api/myservice then your request will go through normally. If however, the service you are trying to access is at http://someotherdomain.net 中执行,那么即使服务器正常响应,浏览器也不会成功完成您的请求。

您必须阅读有关您正在使用的任何网络服务器软件的文档,了解如何在其上设置 headers。当您在服务器上设置 'Access-Control-Allow-Origin': '*' 时,您实际上是在对世界说 - "You can load my data onto any browser application that lives in any domain"。这意味着世界上任何人都可以调用您的服务,如果您想阻止这种情况,您将必须实施身份验证(常见的是 API 密钥模型)。