0

I'm making a request to an authorized Instagram account to display images on a site. Originally, I was running into No 'Access-Control-Allow-Origin' when using Angular's $http.get(....

From Matt's answer in this question, It seems that I can use getJSON, or Angular $http.jsonp, to bypass this issue. That Guy's answer also says "JSONP is really a simply trick to overcome XMLHttpRequest same domain policy".

So, I'm no longer getting that problem, and am getting a json payload:

{"pagination":{"next_url":"https:\/\/api.instagram.com... etc 

But am getting a very ambiguous error:

Uncaught SyntaxError: Unexpected token :

This is a response from the Instagram API, so I'm not sure why there'd be a syntax error on the inbound json. Also, It's hard to locate the error since the jsonp response is all on a single line... where the error is reported.

The preview shows that I'm getting a full payload:

enter image description here

Community
  • 1
  • 1
user3871
  • 12,432
  • 33
  • 128
  • 268
  • 1
    it's not as simple as calling for jsonp if the API doesn't return jsonp. If api isn't CORS enabled or serving jsonp you need to use a proxy, either on your server or a third party service. Just because you see json payload, doesn't mean browser will allow access to it – charlietfl Apr 29 '15 at 17:27

1 Answers1

2

I found the issue. Unfortunately there are no JavaScript libraries to help with this, but in the Instagram API docs, for JSONP you can wrap the response with a callback so that the json payload will be wrapped in <script> tags (more info on jsonp here), therefore not blocked by Access Control Allow Origin.

https://api.instagram.com/v1/tags/coffee/media/recent?access_token=ACCESS-TOKEN&callback=callbackFunction

Response:

callbackFunction({
    ...
});

So, in your http request URI, you add in a callback parameter. Since I am using Angular, their docs for $http.jsonp() requests specify the callback string as "JSON_CALLBACK".

So, my request URL for Angular would be:

$http.jsonp(
    'https://api.instagram.com/v1/tags/coffee/media/recent?
     access_token=ACCESS-TOKEN&callback=JSON_CALLBACK')
     .success(function(data) {...
user3871
  • 12,432
  • 33
  • 128
  • 268