Reputation: 157
I'm walking thru the Angularjs phones tutorial and want to get the phones JSON from a remote server.
$http.get('http://myserver.com/phones.json').success(function(data) {
$scope.phones = data;
});
This failed due to CORS, I was sending an OPTIONS not a GET request, so I added this first line to the controller
delete $http.defaults.headers.common['X-Requested-With'];
I can see now in Charles that a GET not OPTIONS request is being made to myserver.com, and that the phones JSON is in the response. But the http.get is still failing with status 0 and 'data' is null.
Not sure what to try next. Any insights appreciated.
Upvotes: 6
Views: 8543
Reputation: 157
Here's a good tutorial which implements cross-domain GETS using the $http.jsonp method. No hacks to the headers.
http://net.tutsplus.com/tutorials/javascript-ajax/building-a-web-app-from-scratch-in-angularjs/
Upvotes: 0
Reputation: 177
Well, if you are making a cross domain request, it is right to make a OPTION request as a pre-flight request to know if you are allowed to. If the CORS fails your browser will receive the data but it'll throw an error. So, either you put your html in the same domain or add the CORS to your backend (which is more difficult).
Upvotes: 0
Reputation: 4202
It should not be making an OPTIONS request for a GET, so that sounds right. I think what you want to do is:
$http.get('http://myserver.com/phones.json').then(function(data) {
$scope.phones = data;
}, function(err) { alert('Oh no! An error!'});
I think you want to use then()
, which takes two functions as arguments — the first for success, and the second for error. $http.get()
returns a promise which is acted upon by then()
.
Also, you probably want to use $resource
instead of $http
. It provides a higher level of abstraction, and allows for a more reusable style, http://docs.angularjs.org/api/ngResource.$resource
EDIT:
Check out the angular debug tool here. It shows you what is available in scopes, and shows performance data.
Upvotes: 2