Henry Keene
Henry Keene

Reputation: 11

Angular JSON only works with local json files but not urls

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?

Upvotes: 0

Views: 116

Answers (1)

Jonathan Lucas
Jonathan Lucas

Reputation: 21

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")

Upvotes: 2

Related Questions