开发者

Express Node.js framework: How to re-write a URL by replacing one of the named param segments?

开发者 https://www.devze.com 2023-04-01 12:21 出处:网络
In my Express app, I\'d like to perform some redirects when certain params from the route match certain criteria, using a route param pre-condition. As an example, let\'s say I want the para开发者_Sta

In my Express app, I'd like to perform some redirects when certain params from the route match certain criteria, using a route param pre-condition. As an example, let's say I want the para开发者_StackOverflow社区m word to be converted to all upper-case, if it isn't already.

The param word might be present in several different routes, e.g. /:word, /foo/:word, /foo/:word/bar, etc. Fortunately, with route param pre-conditions, these are all handled by the same code, e.g. (code in CoffeeScript):

app.param 'word', (req, res, next, word) ->
  if word isnt word.toUpperCase()
    new_URL = // current URL, but replace word with word.toUpperCase() //
    res.redirect new_URL, 301

My question regards how to construct new_URL, replacing :word with its upper-case equivalent. I want to be able to use the same function to construct new_URL, regardless of which route is currently being used.

I see that there is req.route, but it is undefined. I guess I can access the currently matched route via req.app.routes.routes.get[req._route_index], and then split the path, and re-construct it, but that seems overly complicated. Is there a way to simply iterate the path segments for the current route? Thanks!


I ended up writing a little function to replace a named route parameter with a new value. I'm not sure this is an optimal solution, and it is not a complete solution (it definitely won't work with nob-segment named params like /:from-:to).

replaceRouteParam = (req, param, replacement) ->
  segments = req.app.routes.routes.get[req._route_index].path.split('/')
  new_segments = []
  for segment in segments
    if segment is param
      new_segments.push replacement
    else if segment[0] is ':'
      new_segments.push req.params[segment[1..]]
    else
      new_segments.push segment

  new_segments.join '/'

The advice I got about using this function in multiple locations (my errors, routes, etc, which are in different files) was to put them in a separate file and require it in whichever files need it.

0

精彩评论

暂无评论...
验证码 换一张
取 消