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¶mB=valueB
?
To use this URL in a route with Express:
/api?paramA=valueA¶mB=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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With