5

I am having trouble getting the NYTimes API to return the JSON correctly. I am sure it is something I am doing wrong versus them. I tried this using the ESPN API and it worked fine. Not sure what I am missing. Here is a look at the code.

app.controller('espn', function($scope,$http){
      //var url = "http://api.espn.com/v1/sports/news/headlines/top?limit=9&apikey=n39jrj4s97tvhxym4qgacnrd&callback=JSON_CALLBACK";
      var url = "http://api.nytimes.com/svc/news/v3/content/all/all/.json?&limit=20&api-key=1f6ef65ff5bb290bdcb01da786c788de:2:67858849&callback=JSON_CALLBACK";
     $http.jsonp(url)
        .success( function(data){
            console.log(data);
      });
});

I get this error in my error console. Uncaught SyntaxError: Unexpected token :

Here is the plunker. Plunker

j0hnstew
  • 709
  • 8
  • 25

1 Answers1

3

Sinse you are calling JSONP, it means that the returned json should be wrappet in a function.

for example:

JSON_CALLBACK({"status":"OK"});//this is actually how the server suppose to answer back

So, I see that you send callback=JSON_CALLBACK, but the server does not reply with function call to JSON_CALLBACK

Youll need somehow to force the server to support JSONP

If you go to:
http://api.nytimes.com/svc/news/v3/content/all/all/.json?&limit=20&api-key=1f6ef65ff5bb290bdcb01da786c788de:2:67858849&callback=JSON_CALLBACK
youll see that the server is not responding as JSONP

you can maybe hack it, have a look here:
http://jquery-howto.blogspot.co.il/2013/09/jquery-cross-domain-ajax-request.html

Avi Fatal
  • 1,550
  • 8
  • 8
  • I mean it is up to the server to do such a thing if they want to correct? I don't think I can force the server to do such a thing. – j0hnstew Oct 29 '13 at 21:08
  • you cant, if the API documentation says so, so you will be able to. Sometime api are blocking that in order to prevent robots scanning the ajax servers, but if I look at the server response, you can make your server call their server and than you will return the message to the javascript. – Avi Fatal Oct 29 '13 at 21:09
  • I see that now. So I guess if it doesn't support it, then there is no way of forcing it to, meaning that I will have to use PHP or Python to CURL it then make a request to that file and get the JSON from there...Correct? – j0hnstew Oct 29 '13 at 21:10
  • I edit my answer, you can create your own server calling their server. see the link i published. – Avi Fatal Oct 29 '13 at 21:12
  • I think I'll just write a little server side code to handle this then I'll be good to go. Thanks for helping. – j0hnstew Oct 29 '13 at 21:12