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.
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.
It appears that a regular expression is the way to go:
app.get(/^[/]foo(?=$|[/])/, ...);
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?*', ...)
I had this issue as well and I have to agree that the Regular expression works the best, however with a slight improvement:
app.get('/foo([/].*)?', ...);
This would match:
/foo
/foo/
/foo/what/ever/you/put/after
The /foo/:dummy?*
doesn't really take the optional /
after foo
into account and /foo(/:dummy*)?
doesn't really match correctly.
/foo(/:dummy)?*
kinda works but creates an extra variable as it has both path
and the *
in separate variables, which is inexpedient in this case.
So personally I would stick with the Regular expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With