简体   繁体   中英

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 ?

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.

I ended up using this. This code did exactly what I set out to do in the original question.

router.get('/api', function(req, res) {
    if(typeof req.query.paramA !== 'undefined' && typeof req.query.paramB !== 'undefined') {
    let paramA = req.query.paramA,   
        paramB = req.query.paramB;
    //do something with paramA and paramB
   }
});

It`s easier to define url parameters in router .

Example url : http://www.example.com/api/users/3&0

router.get('/api/users/:id&:pending', function (req, res) {
  console.log(req.params.id);
  console.log(req.params.pending);
});

If you are certain about the GET parameters that are being passed, so you could easily do it like this:

router.get('/api', function(req, res) {
    if(typeof req.params.paramA !== 'undefined' && typeof req.params.paramB !== 'undefined') {
    let paramA = req.params.paramA,   
        paramB = req.params.paramB;
    //do something with paramA and paramB
   }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM