Reputation: 17269
In ExpressJS, how to right the following in one route using RegEx?
app.get('/blog', blog.list);
app.get('/blog/p/:page?', blog.list);
Upvotes: 3
Views: 4761
Reputation: 51460
What the point of using RegExp here? Express patterns is simpler, yet almost as powerful as regular expressions:
app.get('/blog(?:/p/:page([0-9]+)?)?', blog.list);
This route will match all of the following urls:
/blog
/blog/
/blog/p
/blog/p/
/blog/p/123
In blog.list
controller req.params.page
will contain page number or will be undefined
if it wasn't supplied.
Upvotes: 8
Reputation: 6069
It seems like there might be compelling reasons to make these separate routes, but I'm not sure what you are doing with your app.
app.get(/^\/blog(?:\/p\/([0-9]+)?)?/, blog.list);
req.params[0] should be "20" at the route /blog/p/20, with req.params as null
for /blog/p/ or /blog/ but with with both as functional routes.
Upvotes: 0