Angularjs http.get error (but I see that the data was returned)

I go through the Angularjs phone tutorial and want to get JSON phones from a remote server.

$http.get('http://myserver.com/phones.json').success(function(data) { $scope.phones = data; }); 

This failed due to CORS, I did not send OPTIONS a GET request, so I added this first line to the controller

 delete $http.defaults.headers.common['X-Requested-With']; 

Now I can see in Charles that GET not OPTIONS request is being made on myserver.com and that the answer contains JSON phones. But http.get still does not work with status 0, and "data" is null.

Not sure what to try next. Any ideas were appreciated.

+6
source share
3 answers

It should not make an OPTIONS request for a GET, so it sounds right. I think you want to do:

 $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, the second for error. $http.get() returns the promise that then() acts on.

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:

Wool opens> here . It shows you what's available in scope and shows performance data.

+2
source

Well, if you are making a cross-domain request, it is correct to make an OPTION request as a pre-flight request to find out if you are allowed. If CORS fails, your browser will receive the data, but this will cause an error. This way, either you put your html in one domain or add CORS to your server (which is more complicated).

0
source

Here is a good tutorial that implements cross-domain GETS using the $ http.jsonp method. No headings in headings.

http://net.tutsplus.com/tutorials/javascript-ajax/building-a-web-app-from-scratch-in-angularjs/

0
source

Source: https://habr.com/ru/post/952951/


All Articles