restify regular expression on named parameter

て烟熏妆下的殇ゞ 提交于 2019-12-25 14:21:57

问题


I am using the restify 2.8.4.

Understood that named parameter with regular expression is not supported in Mixing regex and :params in route #247

Instead of cobble both logics into one block.

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

I prefer below code structure:

//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
}

Is there a way I can split them into two separate concerns?


回答1:


It looks like you have mostly already done it yourself. Just remove the identifiers from your route and make sure you use regex capture groups.

//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
}

Answer edited to incorporate Cheng Ping Onn's input.



来源:https://stackoverflow.com/questions/32378419/restify-regular-expression-on-named-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!