【发布时间】:2015-10-15 06:25:56
【问题描述】:
我正在学习 angularJS 并尝试在我的应用程序中实现它。
我在 localhost IIS 上托管了一个 RESTful WCF 服务。 它定义了一个 GET 方法来获取文档列表:http://localhost:70/DocumentRESTService.svc/GetDocuments/
现在我正在尝试在我的 Angular 应用程序中使用此服务并显示数据。 以下是代码: HTML:
<html>
<script src="../../dist/js/angular/angular.min.js"></script>
<script src="../../assets/js/one.js"></script>
<body ng-app="myoneapp" ng-controller="oneAppCtrl">
{{"Hello" + "AngularJS"}}
<hr>
<h1> Response from my REST Service </h1>
{{hashValue}}
<hr>
<h1> Response from w3school REST Service </h1>
{{names}}
</body>
</html>
JS:
angular.module('myoneapp', [])
.controller('oneAppCtrl', function($scope,$http){
$scope.documentValue = {};
$http({method: 'GET',
url: 'http://localhost:70/DocumentRESTService.svc/GetDocuments/',
headers:
{
// 'Access-Control-Allow-Origin': 'http://localhost'
}
})
.success(function(data){ alert('Success!'); $scope.documentValue=data;})
.error(function(data){ alert('Error!'); $scope.documentValue=data; alert('Error!' + $scope.documentValue);})
.catch(function(data){ alert('Catch!'); $scope.documentValue= data;});
$http.get("http://www.w3schools.com/angular/customers.php")
.success(function(response) {$scope.names = response.records;});
});
奇怪的行为是这段代码在 IE11 中运行良好,而在 Chrome/Firefox 中无法运行。
以下是 chrome:(for my REST service) 中的响应,而 w3schools 的 REST 服务运行良好。
{"data":null,"status":0,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":" http://localhost:70/DocumentRESTService.svc/GetDocuments/","headers":{"Accept":"application/json, 文本/纯文本,/"}},"statusText":""}
控制台显示以下错误消息。
- [Chrome 控制台:通过从文件系统打开]
XMLHttpRequest 无法加载 http://localhost:70/DocumentRESTService.svc/GetDocuments/。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'file://' 不允许访问。
- [Chrome 控制台:使用方括号托管]
XMLHttpRequest 无法加载 http://localhost:70/DocumentRESTService.svc/GetDocuments/。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问 Origin 'http://127.0.0.1:55969'。
- [Firefox 控制台:]
跨域请求被阻止:同源策略不允许读取位于http://localhost:70/DocumentRESTService.svc/GetDocuments/ 的远程资源。这可以通过将资源移动到同一域或启用 CORS 来解决。
这里的问题很少:
- 为什么 localhost 或 my machineName 被认为是跨域请求?我在同一个域中,不是吗?
- 是否需要在我的服务端进行任何更改才能启用此行为?如果是,WCF 服务在哪里?(基于我阅读的内容here)
- JSONP 在这种情况下有用吗?如果是,我将如何使用它?它是否适用于需要自定义标头的请求?(不太确定它是什么,但在重新搜索时发现很多答案都提到了这一点。阅读链接会有所帮助。)
任何帮助或指导都会有所帮助。
PS:
- IDE:Brackets,如果这很重要的话。
- AngularJS v1.4.3
- 我已经提到了各种 stackoverflow 问题,这些问题涉及到类似的问题 (CORS),其中涉及 $resource 、 $provider 、 $config ,还有一些与删除某些标头并在标头中添加一些值有关。我对此有点天真 - 任何对此的引用都会有所帮助。
【问题讨论】:
-
不同的端口或子域也被浏览器考虑跨域。大概您的页面正在不同的端口上打开?如何为任何服务器环境实施 CORS 到处都有很好的记录……简单的网络搜索。打开页面时也不能使用
file://协议。甚至 CORS 也无济于事 -
您也通过 localhost url 加载页面? (相对于 file:// 或 127.0.0.1)
-
出于兴趣,IE 并不关心 CORS 的端口号——因此您可以使用它进行测试。或者,使用
chrome --args --disable-web-security启动 chrome,它不会对 CORS 进行检查。 -
@TZHX 问题是忘记它已被禁用并在您的机器上留下安全漏洞。启用 CORS 是最理想的 IMO
-
@charlietfl 完全同意,从长远来看——但要开始做一些事情,了解解决方法会很有用。
标签: javascript angularjs wcf rest cors