2

I have an array of ids that I want to pass to the server. The other answers I have seen online describe how to pass these ids as query parameters in the url. I prefer not to use this method because there may be lots of ids. Here is what I have tried:

AngularJS:

console.log('my ids = ' + JSON.stringify(ids)); // ["482944","335392","482593",...]

var data = $.param({
    ids: ids
});

return $http({
    url: 'controller/method',
    method: "GET",
    data: data,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function (result, status, headers, config) {
    return result;
})

Node.js:

app.get('/controller/method', function(req, res) {
    console.log('my ids = ' + JSON.stringify(req.body.ids)); // undefined
    model.find({
        'id_field': { $in: req.body.ids }
    }, function(err, data){
        console.log('ids from query = ' + JSON.stringify(data)); // undefined
        return res.json(data);
    });

});

Why am I getting undefined on the server side? I suspect it's because of my use of $.params, but I'm not sure.

Chris Paterson
  • 1,099
  • 3
  • 18
  • 28

2 Answers2

4

In Rest GET methods uses the URL as the method to transfer information if you want to use the property data in your AJAX call to send more information you need to change the method to a POST method.

So in the server you change your declaration to:

app.post( instead of app.get(

Dalorzo
  • 19,312
  • 7
  • 50
  • 97
1

If you're using ExpressJS server-side, req.body only contains data parsed from the request's body.

With GET requests, data is instead sent in the query-string, since they aren't expected to have bodies.

GET /controller/method?ids[]=482944&ids[]=...

And, the query-string is parsed and assigned to req.query instead.

console.log('my ids = ' + JSON.stringify(req.query.ids));
// ["482944","335392","482593",...]
Community
  • 1
  • 1
Jonathan Lonowski
  • 112,514
  • 31
  • 189
  • 193
  • 2
    Is there a limit on how much data I can send via this method? My concern is that it will break if I am sending a large number of ids. – Chris Paterson Aug 31 '14 at 01:18