从 angularjs 调用 REST 服务时本地主机上的 CORS 问题 [英] CORS issue on localhost while calling REST service from angularjs

查看:30
本文介绍了从 angularjs 调用 REST 服务时本地主机上的 CORS 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 angularJS 并尝试在我的应用程序中实现它.

I am learning angularJS and trying to implement it in my application.

我在本地主机 IIS 上托管了一个 RESTful WCF 服务.它定义了一个 GET 方法来获取文档列表:http://localhost:70/DocumentRESTService.svc/GetDocuments/

I have an RESTful WCF service hosted on localhost IIS. It has a GET method defined to fetch a list of documents : http://localhost:70/DocumentRESTService.svc/GetDocuments/

现在我正在尝试在我的 angular 应用程序中使用此服务并显示数据.以下是代码:HTML :

Now I am trying to consume this service in my angular app and display the data . Following is the code : 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 中却不能运行.

The strange behavior is this code works perfectly fine in IE11 , whereas it doesn't run in Chrome/Firefox.

以下是 chrome:(对于我的 REST 服务) 中的响应,而 w3schools 的 REST 服务工作得很好.

Following is the response in the chrome:(for my REST service) , whereas the REST service from w3schools worked just fine.

{"data":null,"status":0,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":"http://localhost:70/DocumentRESTService.svc/GetDocuments/","headers":{接受":应用程序/json,文本/纯文本,/"}},"statusText":""}

{"data":null,"status":0,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":"http://localhost:70/DocumentRESTService.svc/GetDocuments/","headers":{"Accept":"application/json, text/plain, /"}},"statusText":""}

控制台显示以下错误消息.

Console displayed following error message.

  • [Chrome 控制台:通过从文件系统打开]

XMLHttpRequest 无法加载 http://localhost:70/DocumentRESTService.svc/GetDocuments/.请求的资源上不存在Access-Control-Allow-Origin"标头.因此不允许访问源file://".

XMLHttpRequest cannot load http://localhost:70/DocumentRESTService.svc/GetDocuments/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'file://' is therefore not allowed access.

  • [Chrome 控制台:使用括号托管]

XMLHttpRequest 无法加载 http://localhost:70/DocumentRESTService.svc/GetDocuments/.请求的资源上不存在Access-Control-Allow-Origin"标头.Origin 'http://127.0.0.1:55969' 因此不允许访问.

XMLHttpRequest cannot load http://localhost:70/DocumentRESTService.svc/GetDocuments/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:55969' is therefore not allowed access.

  • [Firefox 控制台:]

跨源请求被阻止:同源策略不允许读取位于 http://localhost 的远程资源:70/DocumentRESTService.svc/GetDocuments/.这可以通过将资源移动到同一个域或启用 CORS 来解决.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:70/DocumentRESTService.svc/GetDocuments/. This can be fixed by moving the resource to the same domain or enabling CORS.

这里的问题很少:

  1. 为什么 localhost 或 my machineName 被认为是跨域请求?我在同一个域中,不是吗?
  2. 是否需要在我的服务端进行任何更改才能启用此行为?如果是,WCF 服务在哪里?(基于我阅读的内容这里)
  3. JSONP 在这种情况下有用吗?如果是,我将如何使用它?它可以处理需要自定义标头的请求吗?(不太确定它是什么,但是在重新搜索时发现了很多提到这一点的答案.阅读链接会有所帮助.)

任何帮助或指导都会有所帮助.

Any help or direction will be helpful.

附:

  • IDE:括号,如果这很重要.
  • AngularJS v1.4.3
  • 我已经提到了各种涉及类似问题 (CORS) 的 stackoverflow 问题,其中涉及 $resource 、 $provider 、 $config ,还有一些与删除某些标头和添加标头中的某个值有关.我对此有点天真 - 对此的任何参考都会有所帮助.

推荐答案

我可以解决这个问题.有几种方法可以做到这一点 - 我正在记下我尝试过的所有内容以及他们的参考资料.

I could resolve this issue. Couple of ways to do so - I am jotting down all that i have tried and their references.

回答问题1.

'Why is localhost or my machineName considered to be a cross-domain request?'

正如@charlietfl 提到的,我研究了这里:不同的端口或子域是还要考虑浏览器跨域.

as @charlietfl mentioned and i Researched here: a different port or subdomain is also consider cross domain by browser.

回答问题2.

'Are there any changes required to do at my service end to enable this behavior?'

是的!服务器端本身需要更改.服务器应该用

YES! the change is required on server end itself. The server should respond to the request with

访问控制允许来源:*

标题.这里 * 可以替换为请求标头本身或根据您的应用程序要求.优秀博客 此处 解释了您使用 WCF REST 服务时的解决方法.您需要向每个服务方法添加以下行(标题)以在您的服务方法中启用 CORS.

header. Here the * could be replaced with the request header itself or as per your application requirement. Excellent blog here explaining the workaround if you're using WCF REST Service. You need to add following line (headers) to each your service method to enable CORS in your service methods.

WebOperationContext.Current.OutgoingResponse.Headers.Add(
访问控制允许来源",*");WebOperationContext.Current.OutgoingResponse.Headers.Add(
访问控制允许方法",POST");WebOperationContext.Current.OutgoingResponse.Headers.Add(
"Access-Control-Allow-Headers", "Content-Type, Accept");

WebOperationContext.Current.OutgoingResponse.Headers.Add(
"Access-Control-Allow-Origin", "*"); WebOperationContext.Current.OutgoingResponse.Headers.Add(
"Access-Control-Allow-Methods", "POST"); WebOperationContext.Current.OutgoingResponse.Headers.Add(
"Access-Control-Allow-Headers", "Content-Type, Accept");

规范此处对于在服务器/客户端上启用 CORS 非常有帮助.

A specification here is very helpful for enabling CORS on server / client.

回答问题 3.

JSONP 主要适用于 GET 请求,并不是最可取的用途,而是最推荐启用 CORS.(我没有过多地探索这个领域,但是 Wiki 和 stackoverflow 文章 此处 非常具有描述性.

JSONP mostly works for GET requests and aren't most advisable use ,rather enabling CORS is most recommended. (I haven't explored this area much but Wiki & stackoverflow article here were very descriptive).

除此之外,出于测试目的,一个不错的 chrome 此处的扩展 可能会有所帮助.它可用于确保应用程序存在 CORS 问题.

Apart from that, for testing purpose, a nice chrome extension here can be helpful. It can be used to assure that the application has CORS issues.

这篇关于从 angularjs 调用 REST 服务时本地主机上的 CORS 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆