解析命名参数的正则表达式

时间:2015-09-03 14:27:58

标签: restify

我正在使用改编2.8.4。

理解不支持带有正则表达式的命名参数 Mixing regex and :params in route #247

而不是将逻辑拼凑成一个块。

server.get ('/user/:id', function (req, res, next) {
  var id = req.params.id; 
  // check with isNaN()
  // if string do this
  // if number do that
}

我更喜欢以下代码结构:

//hit this route when named param is a number
server.get (/user\/:id(\\d+)/, function (req, res, next) {
  var id = req.params.id; 
  // do stuff with id
}

//hit this route when named param is a string
server.get (/user\/:name[A-Za-z]+/, function (req, res, next) {
  var name = req.params.name; 
  // do stuff with name
}

有没有办法可以将它们分成两个独立的问题?

1 个答案:

答案 0 :(得分:0)

看起来你大部分已经自己完成了。只需从路由中删除标识符,并确保使用正则表达式捕获组。

//hit this route when named param is a number
server.get (/user\/(\d+)/, function (req, res, next) {
    var id = req.params[0]; 
    // do stuff with id
}

//hit this route when named param is a string
    server.get (/user\/([A-Za-z]+)/, function (req, res, next) {
    var name = req.params[0]; 
    // do stuff with name
}

答案经过编辑,包含了Cheng Ping Onn的输入。