CORS问题在localhost同时从angularjs调用REST服务 [英] CORS issue on localhost while calling REST service from angularjs

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

问题描述

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



我有一个RESTful WCF服务托管在localhost IIS。
它有一个GET方法,用于获取文档列表: http:// localhost:70 /DocumentRESTService.svc/GetDocuments/



现在我想在我的角度应用程序中使用这项服务,并显示数据。
以下是代码:
HTML:

 < html> 
< script src =../../ dist / js / angular / angular.min.js>< / script>
< script src =../../ assets / js / one.js>< / script>
< body ng-app =myoneappng-controller =oneAppCtrl>
{{Hello+AngularJS}}
< hr>
< h1>来自我的REST服务的响应< / h1>
{{hashValue}}

< hr>
< h1>来自w3school REST服务的响应< / 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 !'); $ 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 ://www.w3schools.com/angular/customers.php)
.success(function(response){$ scope.names = response.records;});
});

奇怪的行为是这个代码在IE11中工作得很好,但它不会运行在Chrome / Firefox。



以下是chrome:(对于我的REST服务)的响应,而来自w3schools的REST服务工作正常。


{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:} p>

控制台显示以下错误讯息。




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



XMLHttpRequest无法加载 http:// localhost:70 / DocumentRESTService.svc / GetDocuments / 。在所请求的资源上没有Access-Control-Allow-Origin头。

] [/ b] [Chrome控制台使用


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




  • [Firefox控制台]



跨原始请求已阻止:同源策略不允许读取 http:// localhost:70 / DocumentRESTService.svc / GetDocuments / 。这可以通过将资源移动到相同的域或启用CORS来修复。



这里的问题很少:


  1. 为什么localhost或我的machineName被视为跨域请求?我在同一个域,不是吗?

  2. 在我的服务端需要做任何更改以启用此行为吗?如果是,WCF服务在哪里?(基于我在此处阅读的内容)

  3. JSONP在这种情况下有用吗?如果是,我将如何使用它?它会工作与需要自定义头的请求吗?(NOt真的肯定是什么,但是重新发现发现很多答案提到这一点,阅读链接将是有帮助的。)

任何帮助或指导都会有帮助。



PS:




  • IDE:括号,如果有意义。

  • AngularJS v1.4.3

  • 我已经引用了各种stackoverflow问题引用类似问题(CORS),涉及$ resource,$ provider,$ config,还有一些与删除一些标题并添加一些值的标题。我对此有点幼稚 - 任何提及这将是有帮助的。


解决方案

解决此问题。
几种方法 - 我记下了我试过的所有和他们的引用。



回答
Ques1。

 '为什么localhost或我的机器名称被视为跨域请求?'



作为@charlietfl提及和i研究此处:不同的端口或子域也通过浏览器考虑跨域。



回答
Ques2。

 我的服务端需要做任何更改才能启用此行为吗?

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


访问控制 - 允许原点:*




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


WebOperationContext.Current.OutgoingResponse。标题.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);


< blockquote>

规范这里对于启用服务器/客户端上的CORS。



回答Ques3。



JSONP主要用于GET请求,最可取的使用,而是启用CORS是最推荐的。 (我没有探索这个区域,但维基& stackoverflow文章这里是非常描述性的)。



除此之外,为了测试目的,还有一个不错的chrome 这里的扩展可以是有帮助的。它可以用来确保应用程序有CORS问题。


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

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/

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;});            
});

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

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":{"Accept":"application/json, text/plain, /"}},"statusText":""}

Console displayed following error message.

  • [Chrome Console:By opening from filesystem]

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 Console:hosted using Brackets]

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 Console:]

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.

The question here are few:

  1. Why is localhost or my machineName considered to be a cross-domain request ? I am in the same domain , ain't I ?
  2. Are there any changes required to do at my service end to enable this behavior? If yes , where in WCF Service ?( based on something i read here )
  3. an JSONP be useful in this case ? If yes , how would i use it ? would it work with requests that need custom headers ?( NOt really sure what it is , but while resarching found a lot of answers mentioning this. reading links will be helpful. )

Any help or direction will be helpful.

P.S:

  • IDE:Brackets , if that matters .
  • AngularJS v1.4.3
  • I have referred various stackoverflow questions referring similar problem (CORS) , which involved $resource , $provider , $config , Also some related to deleting some header and adding some value one of the header. I am bit naive to this - any references to this will be helpful.

解决方案

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

Answer to Ques1.

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

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

Answer to Ques2.

'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

Access-Control-Allow-Origin: *

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(
"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");

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

Answer to Ques3.

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).

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.

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

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