【问题标题】:I get "No 'Access-Control-Allow-Origin' header error " even though I set it [duplicate]我得到“没有'Access-Control-Allow-Origin'标头错误”,即使我设置它[重复]
【发布时间】: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


【解决方案1】:

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

浏览器有一项安全策略,可防止您的 javascript 代码向不在您域内的服务发出请求。例如,如果您的 javascript 代码在 http://example.com 中执行,并且您的目标服务在 http://example.com/api/myservice 中找到,那么您的请求将正常通过。但是,如果您尝试访问的服务位于http://someotherdomain.net,那么即使服务器正常响应,浏览器也不会成功完成您的请求。

您必须阅读有关您正在使用的任何 Web 服务器软件的文档,了解如何在其上设置标头。当您在您的服务器上设置 'Access-Control-Allow-Origin': '*' 时,您实际上是在向全世界说 - “您可以将我的数据加载到任何域中的任何浏览器应用程序中”。这意味着世界上任何人都可以调用您的服务,如果您希望阻止这种情况,您将必须实施身份验证(常见的是 API 密钥模型)。

【讨论】:

    【解决方案2】:

    CORS 标头需要由服务器发送。

    跨域资源共享标准通过添加新的 HTTP 来工作 允许服务器描述源集的标头 允许使用网络浏览器阅读该信息。此外, 对于可能对用户数据造成副作用的 HTTP 请求方法(在 特别是对于 GET 以外的 HTTP 方法,或者对于 POST 使用 某些 MIME 类型),规范要求浏览器 “预检”请求,从服务器请求支持的方法 使用 HTTP OPTIONS 请求方法,然后在“批准”时 服务器,使用实际的 HTTP 请求发送实际的请求 方法。服务器还可以通知客户端是否“凭据” (包括 Cookie 和 HTTP 身份验证数据)应与 请求。

    Read more.

    【讨论】:

      猜你喜欢
      • 2016-08-12
      • 2018-09-19
      • 1970-01-01
      • 2016-04-05
      • 2016-01-21
      • 1970-01-01
      • 2017-07-13
      • 2014-10-21
      • 1970-01-01
      相关资源
      最近更新 更多