3

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.

1
  • req.body is for POST request AFAIK, and you do a get request on your client side. Commented Oct 30, 2013 at 15:56

2 Answers 2

4

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);
        });
    }      
  };
});
Sign up to request clarification or add additional context in comments.

2 Comments

Erik I Accepted your answer. Thank you.
just for clarity - you might also update the code sample when you say change the get to a post: app.post('/courses', function(request, response) { response.send(request.body); }); or it won't work as I just discovered - everything else is awesome!
2

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);   
});

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.