With the following route:
app.get('/', controller.web.Home);
How would I add within '/'
something which would allow a match for /
, /index
and /index.html
? I would also like to use this approach for all other routes so that users don't see an error page when adding .html to a path.
I have seen this mentioned on the Express website, however there are no clear explanations for matching multiples. Thanks in advance.
Express uses path-to-regex for routing strings meaning you can use regular expressions or string patterns to match routes.
How would I add within '/' something which would allow a match for /, /index and /index.html
Something like this would work:
app.get('/|index|index.html', controller.web.Home);
I would also like to use this approach for all other routes so that users don't see an error page when adding .html to a path.
You can also write a small helper function that takes care of this for any route:
function htmlExt(route) {
return route + '|' + route + '.html';
}
And the use it for any route:
app.get(htmlExt('index'), controller.web.Home);
app.get(htmlExt('blog'), controller.web.Blog);
// ...
You can also pass in an array of paths instead so this should also work:
function htmlExt(route) {
return [route, route + '.html'];
}
app.get(htmlExt('index'), controller.web.Home);
Another way would be to use a regex. Perhaps one that accepts a route and an optional .html
extension:
app.get(/index(.html)?/, controller.web.Home);
You can find other useful examples in Express Routing docs.
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