Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express + Node Route With Multiple Parameters in Query String

I am building an API in Node and am struggling to figure something out. Namely, I know how to build routes of the type /api/:paramA/:paramB. In this case, there are two parameters.

The code would be something like this:

router.get('/test/:paramA/:paramB', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' + req.params.paramA + req.params.paramB});   
});

How could one build a route that would respond at something like /api?paramA=valueA&paramB=valueB?

like image 590
MadPhysicist Avatar asked Nov 29 '22 22:11

MadPhysicist


1 Answers

To use this URL in a route with Express:

 /api?paramA=valueA&paramB=valueB

You do this:

router.get('/api', function(req, res) {
    console.log(req.query.paramA);     // valueA
    console.log(req.query.paramB);     // valueB
    console.log(req.query.paramC);     // undefined (doesn't exist)
});

Query parameters are parsed into the req.query object. If the query parameter name does not exist in the query string, then that property will not exist on the query.query object and trying to read it will return undefined. Keep in mind that all values will be strings. If you desire them to be a number or some other data type, then you have to parse them into that other type.

like image 161
jfriend00 Avatar answered Dec 05 '22 14:12

jfriend00