Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs issue $http.get not working

I am a novice to Angularjs and tried to follow example given for $http.get on angularjs website documentation.

I have a REST service, which when invoked returns data as follows:

http://abc.com:8080/Files/REST/v1/list?&filter=FILE


 {
  "files": [
    {
      "filename": "a.json",
      "type": "json",
      "uploaded_ts": "20130321"
    },
    {
      "filename": "b.xml",
      "type": "xml",
      "uploaded_ts": "20130321"
    }       
  ],  
 "num_files": 2}

Part of the contents of my index.html file looks like as follows:

<div class="span6" ng-controller="FetchCtrl">
    <form class="form-horizontal">
        <button class="btn btn-success btn-large" ng-click="fetch()">Search</button>
    </form>
      <h2>File Names</h2>
      <pre>http status code: {{status}}</pre>
     <div ng-repeat="file in data.files">
      <pre>Filename: {{file.filename}}</pre>
    </div>

And my js file looks as follows:

function FetchCtrl($scope, $http, $templateCache) {
  $scope.method = 'GET'; $scope.url = 'http://abc.com:8080/Files/REST/v1/list?&filter=FILE'; 
  $scope.fetch = function() {
    $scope.code = null;
    $scope.response = null;

    $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
      success(function(data, status) {
        $scope.status = status;
        $scope.data = data;
      }).
      error(function(data, status) {
        $scope.data = data || "Request failed";
        $scope.status = status;
    });
  };      
}

But when I run this, I do not see any result for filenames and I see http status code = 0

When I run ,

http://abc.com:8080/Files/REST/v1/list?&filter=FILE
in browser, I still can see desired results (as mentioned above)

I even tried to debug using Firebug in firefox, I see the above URL gets invoked when I hit "Search" button but response looks to be empty. And interestingly in Firebug under URL, it shows

   OPTIONS "Above URL" 

instead of

   GET "Above URL"

Can you please let me know, what I am doing wrong and why I am not able to access JSON data ?

Thanks,

like image 512
SL101 Avatar asked Mar 21 '13 08:03

SL101


People also ask

Which object does the http GET () function return?

response : interceptors get called with http response object. The function is free to modify the response object or create a new one. The function needs to return the response object directly, or as a promise containing the response or a new response object.

How do we pass data and get data using http in angular?

get request Method Syntax: $http. get(url, { params: { params1: values1, params2:values2, params3:values3...... } });

Is HTTP request is synchronous or asynchronous in AngularJS?

The problem is as follows, $http. get is asynchronous, before the response is fetched, the function returns. Therefore the calling function gets the data as empty string.

What is HTTP request in angular?

HttpRequest represents an outgoing request, including URL, method, headers, body, and other request configuration options. Instances should be assumed to be immutable. To modify a HttpRequest , the clone method should be used.


3 Answers

This is because how angular treats CORS requests (Cross-site HTTP requests). Angular adds some extra HTTP headers by default which is why your are seeing OPTIONS request instead of GET. Try removing X-Requested-With HTTP header by adding this line of code:

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

Regarding CORS, following is mentioned on Mozilla Developer Network:

The Cross-Origin Resource Sharing standard works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser.

like image 100
Aziz Shaikh Avatar answered Oct 17 '22 07:10

Aziz Shaikh


I have been having the issue using $resource, which also uses $http.

I noticed that when I used AngularJS 1.0.6 the request would not even show up in Firebug, but when using AngularJS 1.1.4 Firebug would show the GET request and the 200 OK response as well as the correct headers, but an empty response. In fact, the headers also showed that the data was coming back as shown by the "Content-Length" header having the correct content length, and comparing this against a REST Client plugin I was using that was successfully retrieving the data.

After being even further suspicious I decided to try a different browser. I had originally been using Firefox 16.0.1 (and also tried 20.0.1), but when I tried IE 9 (and AngularJS 1.1.4) the code worked properly with no issues at all.

Hopefully this will help you find a workaround. In my case, I noticed that I never had this problem with relative URLs, so I'm changing my app around so that both the app and the API are being served on the same port. This could potentially be an AngularJS bug.

like image 31
reedog117 Avatar answered Oct 17 '22 07:10

reedog117


I had the same problem today with firefox. IE worked fine. I didn't think it was cors at first because like you I got no errors in the console and got a status of 0 back in my error method in angular. In the firefox console I was getting a 200 response back in my headers and a content length, but no actual response message. Firefox used to give you a warning about cross site scripting that would point you in the right direction. I resolved the issue by setting up cors on my api. This is really the best way to go. If you are only using GET with your api you could also try using jsonp this is built right into angular and it is a work around for cors when you do not control the api you are consuming.

$http.jsonp('http://yourapi.com/someurl')
    .success(function (data, status, headers, config) {
        alert("Hooray!");
    })
    .error(function (data, status, headers, config) {
        alert("Dang It!");
    });
like image 2
Scott Avatar answered Oct 17 '22 08:10

Scott