Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Ajax call Angular to Node.js (express.js)

I am trying simple thing. Make ajax call to node express and do something based on it. I am not being able to access req.body, I mean it is empty when debuggin from node.js side

NODE SIDE. I am using:

app.use(express.bodyParser());

and this is mine test method in express:

app.get('/courses', function(request, response) {
  console.log("I have been hit"); //I Am getting here               
});

ANGULAR SIDE:

eventsApp.factory('MainConnector', function($http, $q, $resource ) {
  return {
    mainConnection: function( ) {

      var requestBody = {
        id: 3,
        name: 'testname',
        lastname: 'testlastname'
      }

      $http.get("http://localhost:3000/courses", requestBody)
        .success(function(data, status, headers, config) {
          console.log("this is coming from wherever:" + data);
          $scope.data = data;
        }).error(function(data, status, headers, config) {
          $scope.status = status;
        });
    }      
  };
});

I am trying access (from node side)

req.body.name

But body is always empty, as if I am not sending anything.

like image 386
EnterpriseXL Avatar asked Mar 03 '26 11:03

EnterpriseXL


2 Answers

Your ExpressJS test handler is not actually responding with any data, which is why you get an empty body back. Check out the expressjs site for documentation.

Basically you want something like this

app.get('/courses', function(request, response) {
  console.log("I have been hit"); //I Am getting here
  response.send('hello world');            
});

Secondly you are trying to send data with your get request. If you take a look at the angularjs documentation you will see that $http.get only takes 1 parameter, the url.

This means the AngularJS factory you want is more like this:

eventsApp.factory('MainConnector', function($http, $q, $resource ) {
  return {
    mainConnection: function( ) 
      $http.get("http://localhost:3000/courses")
        .success(function(data) {
          console.log("this is coming from wherever:" + data);
        });
    }      
  };
});

But lets say you did want to send something to the server, what you want is a POST request. This means you update your express handler to respond to POST instead of GET.

app.get('/courses', function(request, response) {
  response.send(request.body);            
});

This is a simple "echo" handler. It will just send back to the client whatever the client sent to it. If you send it "Hello" it will respond "Hello".

And a corresponding AngularJS service factory

eventsApp.factory('MainConnector', function($http, $q, $resource ) {
  return {
    mainConnection: function( )
      var data = {name: "hello"};
      $http.post("http://localhost:3000/courses", data)
        .success(function(data) {
          console.log("this is coming from wherever:" + data);
        });
    }      
  };
});
like image 66
Johanna Larsson Avatar answered Mar 06 '26 01:03

Johanna Larsson


As it turns out to be, this was two problems. Yes, there was this issue using GET and sending payload. However, that did not fix the problem. Problem was in CORS. This is how I fixed it:

var allowCrossDomain = function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'content-type, Authorization, Content-Length, X-Requested-With, Origin, Accept');

    if ('OPTIONS' === req.method) {
        res.send(200);
    } else {
        next();
    }
};

and

app.configure(function () {
    app.set('port', process.env.PORT || 3000);
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(allowCrossDomain);
    app.use(app.router);   
});
like image 30
EnterpriseXL Avatar answered Mar 06 '26 01:03

EnterpriseXL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!