0

I've just been introduced to Angularjs and I was trying to use $http.get. The page only works if the url I give is a local 'calender.json' But when I give a url, it spits out a blank page. Could someone please help me understand my error?

6
  • THIS is CORS issue, check your console.. Commented Jul 15, 2015 at 21:11
  • May need to use jsonp request for CORs. Commented Jul 15, 2015 at 21:13
  • 1
    No 'Access-Control-Allow-Origin' header is present on the requested resource. it appears that you either need to adjust the server or use jsonp. Commented Jul 15, 2015 at 21:14
  • not all API's can be reached using ajax due to same origin policy. This one is not CORS enabled and if they don't serve jsonp you will need to use a proxy to get data. On a side note...strongly suggest upgrading angular version to more current one. A lot of things have changed since 1.02 Commented Jul 15, 2015 at 21:16
  • I found out today that if the url is a 404, chrome sometimes decides to spit out a cross origin error, since a page that can't be found also doesn't have a access-control-allow-origin header. So it can be worth to check if the url that you're trying to fetch actually exists. Commented Jul 15, 2015 at 21:27

1 Answer 1

2

As other have pointed out in the comments to your question, this is a CORS issue. To easily resolve this issue you can change your $http.get() call to $http.jsonp(). This alone will not resolve the issue, however. You will also need to adjust the url by adding another query parameter like so (using your provided url): https://ssl.uh.edu/calendar/api/?view=7day&format=json&distinct=1&callback=JSON_CALLBACK

The callback=JSON_CALLBACK tells the server that you are querying that you want it to wrap the JSON response in a function named JSON_CALLBACK, which is a special angular keyword. Check out the docs for more info: https://docs.angularjs.org/api/ng/service/$http

tl;dr version: change $http.get("https://ssl.uh.edu/calendar/api/?view=7day&format=json&distinct=1") to $http.jsonp("https://ssl.uh.edu/calendar/api/?view=7day&format=json&distinct=1&callback=JSON_CALLBACK")

Sign up to request clarification or add additional context in comments.

3 Comments

good catch that it actually serves jsonp. Worth noting though that the string JSON_CALLBACK is just a placeholder for an internally created callback name
Yeah, I tried to specify that it was special, but didn't want to go on a tangent about it. Thanks for pointing that out.
I only mentioned it because a few days ago I saw someone try to use that string in a static script file to test jsonp and couldn't figure out why it wasn't working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.