Nadav
Nadav

Reputation: 1145

Express - Allowing for a closing / at the end of a routing path

While routing in Express is quite straightforward I'm having trouble adjusting it to paths that end with a /. For example, suggest I define the following route:

app.get('/about', (req,res) => res.render('about'));

Now if someone navigates to www.example.com/about the about view is rendered. However, if that same person navigates to www.example.com/about/ the route I specified above will not work. Some people (me included) have gotten used to naturally adding a closing / at the end of paths. I read the Express routing documentation page but it seems the developers were oblivious to this possibility. The only solution I've found thus far is to use regular expressions for each and every route to account for this variation. For example, the route above would become:

app.get(/\/about\/?/, (req,res) => res.render('about'));

Is there a more elegant (or built in) solution to allow for path with a closing / in Express?

Upvotes: 0

Views: 1601

Answers (1)

Muthukumar
Muthukumar

Reputation: 9579

This question has already been answered in https://stackoverflow.com/a/15773824/515774

Basically, you will need to add a middleware which will strip the trailing slash and make a redirect request, which will solve your problem.

Following is the code snippet from the previous answer.

app.use(function(req, res, next) {
    if (req.path.substr(-1) == '/' && req.path.length > 1) {
        var query = req.url.slice(req.path.length);
        res.redirect(301, req.path.slice(0, -1) + query);
    } else {
        next();
    }
});

To avoid redirect, you can just rewrite the URL. Reference https://stackoverflow.com/a/13446128/515774

Note: The browser URL stays the same using this approach.

app.use(function(req, res, next) {
  if (req.url.slice(-1) === '/') {
    req.url = req.url.slice(0, -1);
  }
  next();
});

Upvotes: 1

Related Questions