Passing route control with optional parameter after root in express?

后端 未结 2 536
时光取名叫无心
时光取名叫无心 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:08

    That would work depending on what client.get does when passed undefined as its first parameter.

    Something like this would be safer:

    app.get('/:key?', function(req, res, next) {
        var key = req.params.key;
        if (!key) {
            next();
            return;
        }
        client.get(key, function(err, reply) {
            if(client.get(reply)) {
                res.redirect(reply);
            }
            else {
                res.render('index', {
                    link: null
                });
            }
        });
    });
    

    There's no problem in calling next() inside the callback.

    According to this, handlers are invoked in the order that they are added, so as long as your next route is app.get('/', ...) it will be called if there is no key.

    0 讨论(0)
  • 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
    

    0 讨论(0)
提交回复
热议问题