davidchambers davidchambers - 2 months ago 15
Node.js Question

Express: Optional trailing slash for top-level path

Update: My question did not accurately convey what I'm trying to achieve. I wish to match

/foo
,
/foo/
, and anything under
/foo/
(e.g.
/foo/asdf/jkl
), not the given paths specifically. The original question follows.




I'd like to match the following paths:

/foo
/foo/bar
/foo/bar/baz


These should work, too:

/foo/ -> /foo
/foo/bar/ -> /foo/bar
/foo/bar/baz/ -> /foo/bar/baz


I tried the following:

app.get('/foo/*', ...);


This fails in the
/foo
case, though. I know that I can provide a regular expression rather than a string, but this is surely a common requirement so I'd be surprised to learn that the pattern-matching DSL does not accommodate it.

Answer

It appears that a regular expression is the way to go:

app.get(/^[/]foo(?=$|[/])/, ...);
Comments