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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6784753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:23:50  来源:igfitidea点击:

Passing route control with optional parameter after root in express?

node.jsroutesexpress

提问by Qcom

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

我正在开发一个简单的 url-shortening 应用程序,并具有以下快速路由:

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
      });
    }
  });
});

I would like to remove the /l/from my route (to make my url's shorter) and make the :key parameter optional. Would this be the correct way to do this:

我想/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
  });
});

Not sure if I need to specify that my /route is the one to be "nexted" to. But since my only other route would be my updated post /route, I would imagine it would work fine.

不确定我是否需要指定我的/路线是“下一步”的路线。但由于我唯一的其他路线将是我更新后的/路线,我想它会正常工作。

回答by Ernesto Badillo

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

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

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.

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

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.

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

回答by Lord

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:

可选参数非常方便,您可以使用 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 batchNois optional. Express will count it optional because after in URL construction, I gave a '?' symbol after batchNo '/:batchNo?'

在上面的代码中,batchNo是可选的。Express 会认为它是可选的,因为在 URL 构建之后,我给出了一个 '?' batchNo 后的符号 '/:batchNo?'

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

现在我只能使用 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

enter image description hereenter image description here

在此处输入图片说明在此处输入图片说明