Skip to content

Instantly share code, notes, and snippets.

@imWildCat
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imWildCat/971ec15462757e8029ad to your computer and use it in GitHub Desktop.
Save imWildCat/971ec15462757e8029ad to your computer and use it in GitHub Desktop.
Express Regx Param
// 如下,想限制匹配长度等于24的字符串,因为ID是mongodb的id
// Sample in Expressjs.com
router.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');
}
}
}
});
apiRouter.param('id',/[0-9a-f]{24}/);
// My code
apiRouter.param(function(name, fn){
if (fn instanceof RegExp) {
return function(req, res, next, val){
if(val.match(fn)){
console.log(val.match(fn));
next();
} else {
console.error(val.match(fn));
next('route');
}
}
}
});
apiRouter.param('id',/[0-9a-f]{24}/);
// 如果我改为下面的代码,能排除小于24的,但是我只想匹配长度等于24的
apiRouter.param('id',/[0-9a-f]{24},/);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment