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.
Solution 1:
It appears that a regular expression is the way to go:
app.get(/^[/]foo(?=$|[/])/, ...);
Solution 2:
I know this is an old question, but I had the same issue and I came up with this:
app.get(['/foo', '/foo/*'], ...);
This will match /foo
, /foo/
, and anything under /foo/...
. I think this is a more readable solution than a regular expression and it communicates clearly what is intended.
Solution 3:
If you want to match them in one pattern:
app.get('/foo(/bar(/baz)?)?', ...)
The default Express behaviour of allowing an optional /
at the end applies.
EDIT: how about this?
app.get('/foo/:dummy?*', ...)