Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS routes with or without file extensions

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.

like image 943
stackunderflow Avatar asked Jan 07 '23 15:01

stackunderflow


1 Answers

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);
// ...

Other approaches

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.

like image 53
nem035 Avatar answered Jan 18 '23 05:01

nem035