Bhramar Bhramar - 5 months ago 77
AngularJS Question

CORS issue on localhost while calling REST service from angularjs

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.


Answer

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.

Comments