0

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?

Nadav
  • 1,055
  • 1
  • 10
  • 23
  • http apache standered /about/ mean /about/index.html and web framenwork use same thing as like /about/index.php, where are you confusing – shivshankar Dec 12 '17 at 04:47
  • Yes. The sentence I wrote was a bit misleading. I'll remove it since a PHP MVC comparison doesn't really help in resolving this issue. – Nadav Dec 15 '17 at 02:37

1 Answers1

1

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();
});
Muthukumar
  • 8,679
  • 17
  • 61
  • 86
  • 1
    Thank you very much for showing me the answer. It was hard to explain this issue and hence also hard to search for it (the terminology is pretty fuzzy). That is an excellent solution. – Nadav Dec 12 '17 at 08:30
  • Unfortunately the solution you wrote above requires a redirect. Redirecting is more time consuming than using a regex. Is there no way to change the path Express uses to check against app.get(path, callback) before Express reaches the app.get method? – Nadav Dec 12 '17 at 16:51
  • @Nadav Updated the answer – Muthukumar Dec 12 '17 at 16:57