Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 458
davidchambers Avatar asked May 16 '13 00:05

davidchambers


4 Answers

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.

like image 181
Noam Bendelac Avatar answered Nov 15 '22 03:11

Noam Bendelac


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

app.get(/^[/]foo(?=$|[/])/, ...);
like image 28
davidchambers Avatar answered Nov 15 '22 02:11

davidchambers


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?*', ...)
like image 5
robertklep Avatar answered Nov 15 '22 03:11

robertklep


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.

like image 3
Tokimon Avatar answered Nov 15 '22 02:11

Tokimon