0

this will probably make me look like a total beginner and I am when it comes to angular, but here's my question:

I'm trying to make a simple request to a .JSON api but I just keep getting the error status code 0.

var dataUrl = 'http://www.reddit.com/r/pics/comments/1ua1nb/.json?limit=2';

$http({method: 'GET', url: dataUrl}).
    success(function(data, status, headers, config)
    {
        window.alert('success:' + status);
    }).
    error(function(data, status, headers, config) {
        window.alert('error:' + status);
    });

Update:

I checked the javascript console via the browser and got these error messages:

event.returnValue is deprecated. Please use the standard event.preventDefault() instead. Failed to load resource: the server responded with a status of 501 (Not Implemented) http://www.reddit.com/r/pics/comments/1ua1nb/.json?limit=2 Failed to load resource: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ... is therefore not allowed access. http://www.reddit.com/r/pics/comments/1ua1nb/.json?limit=2 XMLHttpRequest cannot load http://www.reddit.com/r/pics/comments/1ua1nb/.json?limit=2. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ... is therefore not allowed access.

user1354603
  • 4,034
  • 4
  • 31
  • 43

2 Answers2

2

You are trying to do a cross-domain request. This is forbidden by browser (it will only let you make requests to the same domain as your page was initially loaded from). This is not specific to angular, but just ajax requests in general.

You can read about it here:

http://en.wikipedia.org/wiki/Same-origin_policy

There are several ways around it, such as JSONP and CORS. Both require server-side support. You would have to look at the service you are calling to see which it might support.

You can read about how to do a JSONP request here:

http://docs.angularjs.org/api/ng.$http

Daniel Tabuenca
  • 13,147
  • 3
  • 35
  • 38
  • that reddit response have `access-control-allow-origin:*` header though – YOU Jan 03 '14 at 09:17
  • You are right, but something must be interfering with his headers (maybe some weird proxy). It works here: http://plnkr.co/edit/sF3MXrgouCqb9AosNAe4?p=preview – Daniel Tabuenca Jan 03 '14 at 09:28
0

You are not allowed to access resource on another website.

You need to use jsonp.

This is an un-tested modified code of yours, please try it to see whether it's working or not:

var dataUrl = 'http://www.reddit.com/r/pics/comments/1ua1nb/.json?jsonp=JSON_CALLBACK&limit=2';

$http.jsonp(dataUrl).
    success(function(data, status, headers, config)
    {
        window.alert('success:' + status);
    }).
    error(function(data, status, headers, config) {
        window.alert('error:' + status);
    });

more to read: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

Rowanto
  • 2,819
  • 3
  • 18
  • 26