kentor
kentor

Reputation: 18504

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.

Upvotes: 3

Views: 3489

Answers (2)

Relu Mesaros
Relu Mesaros

Reputation: 5038

Hope it helps

router.get('/players', function(req, res) {

    console.log(req.query) // should return the query string

    var searchTerm = req.term;
    console.log("Term: " + JSON.stringify(req.params));
    res.json({"result": "Account deleted"});
});

Upvotes: 1

gibson
gibson

Reputation: 1086

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) {

Upvotes: 5

Related Questions