在express中root后用可选参数传递路由控制?

Qco*_*com 74 routes node.js express

我正在开发一个简单的网址缩短应用程序,并有以下快速路线:

app.get('/', function(req, res){
  res.render('index', {
    link: null
  });
});

app.post('/', function(req, res){
  function makeRandom(){
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 3 /*y u looking at me <33??*/; i++ )
      text += possible.charAt(Math.floor(Math.random() * possible.length));
    return text;
  }
  var url = req.body.user.url;
  var key = makeRandom();
  client.set(key, url);
  var link = 'http://50.22.248.74/l/' + key;
  res.render('index', {
    link: link
  });
  console.log(url);
  console.log(key);
});

app.get('/l/:key', function(req, res){
  client.get(req.params.key, function(err, reply){
    if(client.get(reply)){
      res.redirect(reply);
    }
    else{
      res.render('index', {
        link: null
      });
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

我想/l/从我的路线中移除(使我的网址变短)并使:key参数可选.这是否是正确的方法:

app.get('/:key?', function(req, res, next){
  client.get(req.params.key, function(err, reply){
    if(client.get(reply)){
      res.redirect(reply);
    }
    else{
      next();
    }
  });
});

app.get('/', function(req, res){
  res.render('index, {
    link: null
  });
});
Run Code Online (Sandbox Code Playgroud)

不确定我是否需要指定我的/路线是"nexted"的路线.但由于我唯一的其他路线是我更新的/邮路,我想它会工作正常.

小智 167

这将取决于client.get在将undefined作为其第一个参数传递时的作用.

像这样的东西会更安全:

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
            });
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

在回调中调用next()没有问题.

根据这个,处理程序按照它们被添加的顺序被调用,因此只要你的下一个路由是app.get('/',...),如果没有键就会被调用.


Lor*_*ord 11

快递版本:

"dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1"
  }
Run Code Online (Sandbox Code Playgroud)

可选参数非常方便,您可以使用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);
    }
});
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,batchNo是可选的。Express 会将其视为可选,因为在 URL 构造之后,我给出了一个“?” batchNo '/:batchNo?' 之后的符号

现在我可以仅使用categoryId 和productId 进行调用,或者使用所有三个参数进行调用。

http://127.0.0.1:3000/api/v1/tours/5/10
//or
http://127.0.0.1:3000/api/v1/tours/5/10/8987
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述 在此输入图像描述