我得到了" No' Access-Control-Allow-Origin'标题错误"即使我设置它

时间:2016-07-10 13:11:19

标签: javascript angularjs http-headers xmlhttprequest

我遇到此错误,即使我在角度$ 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"}]

2 个答案:

答案 0 :(得分:2)

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

  

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

Read more.

答案 1 :(得分:2)

您的问题与“访问控制 - 允许 - 来源”&#39;:&#39; *&#39;需要在服务器上设置。通过执行此操作,您启用CORS(跨源资源共享)

浏览器的安全策略会阻止您的javascript代码向不在您域中的服务发出请求。例如,如果您的javascript代码在http://example.com中执行,而您定位的服务位于http://example.com/api/myservice,则您的请求将正常运行。但是,如果您尝试访问的服务位于http://someotherdomain.net,则即使服务器响应正常,浏览器也无法成功完成您的请求。

您必须阅读有关如何在其上设置标头的任何网络服务器软件的文档。当您设置“访问控制 - 允许 - 来源”&#39;:&#39; *&#39;在您的服务器上,您实际上是在向世界说 - &#34;您可以将我的数据加载到任何域中的任何浏览器应用程序中#34;。这意味着世界上任何人都可以调用您的服务,如果您希望阻止这种情况,您将必须实现身份验证(这是常见的API密钥模型)。