1

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.

6
  • What do you see in the browser console? Are you fighting the Same-Origin Policy? Commented May 17, 2016 at 21:58
  • @SLaks does same host, different port count as same origin? Commented May 17, 2016 at 22:08
  • @SLaks... ahh. the console! yes, it does indicate an "Access-Control-Allow-Origin header is present on the requested resource. ... is therefore not allowed. I'm going to google that now to see if I can learn how to fix. Thanks for the helpful tip. Commented May 17, 2016 at 22:13
  • Basically you need to set Access-Control-Allow-Origin header to localhost:9000 on server side. (Although, if you host it on localhost only, not publicly, you can just set it to *.) Commented May 17, 2016 at 22:16
  • @JohnSmith - big help, Thanks! Do you want to make that an answer so I can check it off? Commented May 17, 2016 at 22:20

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.