问题
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