Bra*_*oss 4 regex node.js express
我试图找到一种方法将正则表达式输入到快速路由URL中,然后通过请求对象访问URL的变量部分.具体来说,我想路由到网址"/ posts /"+任意数量的数字.有没有办法做到这一点?
例子:
/posts/54
/posts/2
/posts/546
Run Code Online (Sandbox Code Playgroud)
这应该这样做:
app.get('/posts/:id(\\d+)', function(req, res) {
// id portion of the request is available as req.params.id
});
Run Code Online (Sandbox Code Playgroud)
编辑:将正则表达式添加到路径以将其限制为数字
我同意约翰尼的观点,我唯一的补充是你可以在任意数量的级别上执行此操作。例如:
app.get('/users/:id/:karma', function(req, res){
//Both req.params.id and req.params.karma are available parameters.
});
Run Code Online (Sandbox Code Playgroud)
您还应该查看 Express 文档:http://expressjs.com/api.html。请求部分可能对您非常有用。