5

we are currently developing a little AngularJS project and starting from the frontend, so pure HTML and JavaScript.

However, we need to make some API calls using ngResource. At the moment we are using canned to mock the json return value.

Say this returns a JSON:

GET http://ip-address/something/1.json

I want to be able to call this from ngResource:

app.controller('SomethingCtrl', function ($scope, $resource) {
  Something = $resource("http://ip-address/something/:id", {id: "@id"});
  $scope.something = Something.get({id:1});
});

For some reason this does not work, although the endpoint is working correctly. Angular just makes an option request to this URL.

Is this some kind of XSS protection magic and how do I solve it?

Update: Added the IP-Address to example

EDIT:

I have changed the mock API server, so that CORS is allowed.

I return now this header and the OPTIONS request goes through

Access-Control-Allow-Headers:X-Requested-With
Access-Control-Allow-Max-Age:86400
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, HEAD, OPTIONS
Access-Control-Allow-Origin:*

But now, the get request gets cancelled (no response gets returned). So I suppose Angular does some kind of magic.

leifg
  • 8,668
  • 13
  • 53
  • 79
  • 1
    you can look at JSONP if the external API supports JSONP – Abhishek Nandi Jun 14 '13 at 12:25
  • 1
    The first parameter to _$resource_ should be the complete URL `http://ip-address/something/:id.json` – remigio Jun 14 '13 at 12:30
  • Does your Angular App and "canned" resource run on same domain:port? If not, then [Jquery: Why am I getting an OPTIONS request insted of a GET request?](http://stackoverflow.com/questions/1256593/jquery-why-am-i-getting-an-options-request-insted-of-a-get-request). – Stewie Jun 14 '13 at 12:33
  • well, was a copy and paste mistake. I actually used the IP-Address in the url – leifg Jun 14 '13 at 13:02

1 Answers1

9

Ok I figured it out. You need to inject the $http service and set the useXDomain flag.

app.controller('SomethingCtrl', function ($scope, $http, $resource) {
  $http.defaults.useXDomain = true;
  Something = $resource("http://ip-address/something/:id", {id: "@id"});
  $scope.something = Something.get({id:1});
});

Furthermore. Every request to the service must return the correct CORS headers (not only the OPTIONS request)

leifg
  • 8,668
  • 13
  • 53
  • 79
  • There is no such thing as `useXDomain` in Angular. It never made into the Angular code. https://github.com/angular/angular.js/issues/2956 – Onur Yıldırım Dec 16 '14 at 04:08