3

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.

2 Answers 2

5

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) {
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the additional explanation, helped a lot to sort my confusion about other answers.
1

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"});
});

Comments

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.