1

I am new to AngularJS & NodeJS. I am trying to get a API response from NodeJS and display it in angular. I am using $http to make API call. Below is my nodeJS code.

var express = require('express');
var app = express();
app.get('/employees',function(req,res)
{
 console.log("Test Output :");
 res.status(200).send('Hello User');
});
app.listen(8080);

Below is my angular code

var myapp = angular.module('myapp',[]).controller('myappController',    ['$scope','$http',function ($scope,$http){
$http.get('http://127.0.0.1:8080/employees')
    .then(function(response)
    {
         window.alert("Success");
         $scope.emdata=response.data;
    },function(errorresponse)
    {
         window.alert("Error");
         $scope.emdata=errorresponse.status;
    });
}]);

I am using expression {{emdata}} in HTML page. When I open the HTML page I can see the console output "Test Output " in NodeJS terminal which means the API is getting called but I dont see "Hello User" in HTML page. It looks like the success function in $http.get is not getting called and only the error function is getting called. So I see an alert window with "Error" whenever I open the HTML page and response status as -1 in the place of {{emdata}}.

When I tried making the API call using Postman I get correct response with status 200. So I am wondering what is wrong?

ryanyuyu
  • 6,366
  • 10
  • 48
  • 53
Tommy
  • 11
  • 3
  • Hey bro try this :`$http.get('/employees/', $scope.initial).success(function(response) { });` and try sending a json response perhaps from the server because that way it stays neat and clean. `res.json({status: 200, message: 'message' }); ` – Gandalf the White May 21 '16 at 17:50
  • @GandalftheWhite `.success` and `.error` are deprecated – Clint May 21 '16 at 17:52
  • I never knew. What is the alternative then, the format he is using? It don't look that neat or an upgrade for sure. – Gandalf the White May 21 '16 at 17:54
  • @GandalftheWhite Yes, [an explanation to deprecation reason](http://stackoverflow.com/a/35331339/6275781). – Clint May 21 '16 at 18:02
  • If you open html page in your browser from filesystem and then try to get from nodejs server so you can face the CORS problem. Just open browser console (ctrl + shift + j in chrome) and check network request plus js errors – Denis Yakovlev May 21 '16 at 18:13

1 Answers1

0

Check headers, i.e. what format is accepted by $http request and the format of the response (JSON, plain text, etc).

Fix value in

$httpProvider.defaults.headers.common

or set needed one in

$httpProvider.defaults.headers.get = { ... };

or just use

var requestParams = {
    method: 'GET',
    url: '...',
    headers: {
        ...
    }
};
$http(requestParams).then(...);

Take a look at Setting HTTP Headers in official manual for more details.

marbug
  • 340
  • 2
  • 10