stackunderflow
stackunderflow

Reputation: 1714

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.

Upvotes: 4

Views: 3484

Answers (4)

nem035
nem035

Reputation: 35491

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.

Upvotes: 6

Lukasz Wiktor
Lukasz Wiktor

Reputation: 20422

If you want a global approach you can use a middleware function. Put it before all of your routes.

app.use(function(req, res, next) {
    var match = req.path.match(/(.*)\.html$/)
    if (match !== null) {
        res.redirect(match[1]);
    } else {
        next();    
    }
});

It redirects every path ending with .html to a route without this extension. Of course the route path '/' needs to be handled separately.

Upvotes: 0

Lukasz Wiktor
Lukasz Wiktor

Reputation: 20422

You can define an array of paths as the first argument:

app.get(['/', '/index' , '/index.html'], controller.web.Home);

Upvotes: 3

Simone Sanfratello
Simone Sanfratello

Reputation: 1610

using express 4.x

app.get('/(index*)?', controller.web.Home);

reference http://expressjs.com/en/guide/routing.html

Upvotes: 0

Related Questions