RegEx help-快速路由网址

时间:2013-10-14 18:51:41

标签: regex node.js express routes

我从其他Stack Overflow帖子中读到,您可以使用正则表达式来路由各种URL。我之前从未真正使用过RegExps,所以我需要一些帮助。如何路由以/ lobby /后跟十位数字开头的所有网址?像这样

app.get("/lobby/0000000000", function (req, res) ...

感谢。

2 个答案:

答案 0 :(得分:9)

这是一个有效的例子:

app.get(/^\/lobby\/[0-9]{10}$/, function(req, res) {
  // route handler here
});

或者,您可以使用参数检查:

app.param(function(name, fn){
  if (fn instanceof RegExp) {
    return function(req, res, next, val){
      var captures;
      if (captures = fn.exec(String(val))) {
        req.params[name] = captures;
        next();
      } else {
        next('route');
      }
    }
  }
});

app.param('id', /^[0-9]{10}$/);
app.get('/lobby/:id', function(req, res){
  res.send('user ' + req.params.id);
});

答案 1 :(得分:5)

app.get('/lobby/:id', function(req, res){
    console.log( req.params.id );
    res.end();
});

app.get('/lobby/((\\d+))', function(req, res){
    console.log( req.params[0] );
    res.end();
});

或者如果网址必须是10位数字:

app.get('/lobby/((\\d+){10})', function(req, res){
    console.log( req.params[0] );
    res.end();
});