kentor kentor - 6 months ago 14
Node.js Question

Retrieve multiple GET parameters with Express

I try to retrieve multiple GET parameters with Express, but req.params is always empty. I am not entirely sure how to do it properly with Express 4 as the answers vary a lot because there has changed a lot with newer releases of Express/Node.js I guess.

This is my URL call:

http://localhost:3000/accounts/players?term=asddsa&_type=query&q=asddsa


The http status code is actually 200 so this address actually exists.

This is my router:

router.get('/players', function(req, res) {
var searchTerm = req.term;
console.log("Term: " + JSON.stringify(req.params));
res.json({"result": "Account deleted"});
});


Console log output is:

Term: {}


I have tried different things such as:

router.get('/players/:term/:_type/:q', function(req, res) {


But this caused a 404 for the GET request.

Answer

When you enter the url parameters after the '?' as you did - the parameters will be under req.query rather than req.params, like so:

router.get('/players', function(req, res) {
    var searchTerm = req.term;
    console.log("Term: " + JSON.stringify(req.query));
    res.json({"result": "Account deleted"});
});

If you want to use params instead - your url should look like this:

http://localhost:3000/accounts/players/asddsa/query/asddsa

And the router function can be written as you tried:

router.get('/players/:term/:_type/:q', function(req, res) {
Comments