how to add query parameters to router.get

Viewed 4796

Environment: MEAN tech stack

Hi, I want to add a query parameter to my router.get but I'm not sure how to define it.

Works like this right now:

http://test.com/path1/path2/1

router.get('/path1/path2/:userId', (req, res) => {
    let route = `GET /path1/path2/${req.params.userId}`;

I just want to add a search query parameter, would it be something like this?

http://test.com/path1/path2/1?q=test

And how would that get defined in the router.get?

3 Answers

You do not need to add a query parameter to your route directly. Just keep /path1/path2/:userId.

Within your function you can then check, if a query parameter exists, here via req.query.q.

// http://test.com/path1/path2/1?q=test
router.get('/path1/path2/:userId', (req, res) => {
    let route = `GET /path1/path2/${req.params.userId}`;

    // If http://test.com/path1/path2/1, req.query.q is undefined
    console.log(req.params.userId, req.query.q);
});

You use the req.query object to get query parameters.

So, for the URL http://test.com/path1/path2/1?q=test, you could get the query parameter like this:

router.get('/path1/path2/:userId', (req, res) => {
    console.log(req.params.userId);        // "1"
    console.log(req.query.q);              // "test"
});

Doc for req.query is here.

Related