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.
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(
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",...]