Passing route control with optional parameter after root in express?

后端 未结 2 546
时光取名叫无心
时光取名叫无心 2020-12-05 03:42

I\'m working on a simple url-shortening app and have the following express routes:

app.get(\'/\', function(req, res){
  res.render(\'index\', {
    link: nul         


        
2条回答
  •  天涯浪人
    2020-12-05 04:21

    Express version:

    "dependencies": {
        "body-parser": "^1.19.0",
        "express": "^4.17.1"
      }
    

    Optional parameter are very much handy, you can declare and use them easily using express:

    app.get('/api/v1/tours/:cId/:pId/:batchNo?', (req, res)=>{
        console.log("category Id: "+req.params.cId);
        console.log("product ID: "+req.params.pId);
        if (req.params.batchNo){
            console.log("Batch No: "+req.params.batchNo);
        }
    });
    

    In the above code batchNo is optional. Express will count it optional because after in URL construction, I gave a '?' symbol after batchNo '/:batchNo?'

    Now I can call with only categoryId and productId or with all three-parameter.

    http://127.0.0.1:3000/api/v1/tours/5/10
    //or
    http://127.0.0.1:3000/api/v1/tours/5/10/8987
    

提交回复
热议问题