简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM