Named routes in param pre-conditions

回眸只為那壹抹淺笑 提交于 2019-12-08 04:58:46

问题


I'd like to use a Route Param Pre-Condition to fetch portfolio items by "slug" if the :slug parameter is set in the URL. I also, however, would like to use a RegExp to match the URI. Are named captures supported in node? Can I give that ([-\w]+) capture a name so the slug pre-condition gets fired?

app.param('slug', function(req, res, next, slug){
  // get thing from database by slug
})

//app.get('/work/view/:slug', function(req, res){
app.get(/^\/work\/view\/([-\w]+)/, function(req, res){
  // render view
})

回答1:


I'm not sure if this is what you are looking for, but as far as I know, there is no direct way do do what you need. However, you can use a named param ("slug") and add a Regex precodition along with your own to achieve the same effect.

Take a look at visionmedia's express-params module here. I expect it to be maintained just fine since it's from the creator of express itself.

What you are gonna do (after installing express-params) is basically something like this:

app.param('slug', /^[-\w]+$/);

app.param('slug', function(req, res, next, slug){
  // get thing from database by slug
});

app.get('/work/view/:slug', function(req, res){
  //render view
});

I did not test any of this though.



来源:https://stackoverflow.com/questions/9626193/named-routes-in-param-pre-conditions

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