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.

0

2 Answers 2

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(

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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.

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.