user1272965
user1272965

Reputation: 3064

Angular app $http request to node app on localhost

I'm running a nodejs app on localhost:3000. I have a front-end tutorial angular page that calls localhost like this...

  $scope.msg = 'requesting';
  $http({
    method: 'GET',
    url: 'http://localhost:3000/'
  }).then(function(response) {
    $scope.msg = response;
  }, function(response) {
    $scope.msg = 'err ' + JSON.stringify(response);
  });

I can see from the console on my node app that it is answering with 200 and a json object {foo:'bar'}. But the $scope.msg variable ends up looking like this...

err {  
   "data":null,
   "status":-1,
   "config":{  
      "method":"GET",
      "transformRequest":[  
         null
      ],
      "transformResponse":[  
         null
      ],
      "url":"http://localhost:3000/",
      "headers":{  
         "Accept":"application/json, text/plain, */*"
      }
   },
   "statusText":""
}

Why would the client think there's a problem when the server produced a good response? Running the request in the browser works fine.

Loading the angular page (http://localhost:9000) the browser dev tools, I see this...

enter image description here

But for some reason, the response tab is empty. When I make the same request (http://localhost:3000/) with the browser and watch, I see the JSON in the response tab.

Upvotes: 1

Views: 867

Answers (2)

John Smith
John Smith

Reputation: 2341

As SLaks mentioned in the comment, it happens because of the Same-Origin Policy. Your node app is running on localhost:3000, while your client is on localhost:9000.

You'll need to set Access-Control-Allow-Origin header on server side to allow requests coming from localhost:9000.

Upvotes: 2

Mathieu Seiler
Mathieu Seiler

Reputation: 747

Make sure your server reply with a correct content type header:

Content-Type:application/json; charset=utf-8

Upvotes: -1

Related Questions