16

I'm working on a basic blog in Express.js. Say I have route structure like this:

/blog/page/:page

I would also like a /blog route that is essentially an alias for /blog/page/1. How can I handle this easily in Express?

All routes are defined like such:

app.get('/path', function(req, res) {
    //logic
});
David Adrian
  • 1,079
  • 2
  • 9
  • 24

1 Answers1

30

Use res.redirect to tell the browser to redirect to /blog/page/1:

app.get('/blog', function(req, res) {
    res.redirect('/blog/page/1');
});

app.get('/blog/page/:page', function(req, res) {
    //logic
});

Use a shared route handler and default to page 1 if the page param is not passed:

function blogPageHandler(req, res) {
    var page = req.params.page || 1;
    //logic
}

// Define separate routes
app.get('/blog/page/:page', blogPageHandler);
app.get('/', blogPage);

// or combined, by passing an array
app.get(['/', '/blog/page/:page'], blogPageHandler);

// or using optional regex matching (this is not recommended)
app.get('/:_(blog/)?:_(page/)?:page([0-9]+)?', blogPageHandler);
mekwall
  • 28,614
  • 6
  • 75
  • 77
  • 9
    This will cause a change of the browser's url. You can use connect-modrewrite to rewrite the url instead. https://github.com/tinganho/connect-modrewrite?source=c – einstein Aug 30 '13 at 02:33
  • 3
    Correct @einstein however it's not necessary when using express routes. You can use regex to match, or even pass an array, see here: http://stackoverflow.com/questions/15350025/express-js-single-routing-handler-for-multiple-routes-in-a-single-line – TMPilot Mar 07 '16 at 15:32
  • 6
    downvoted as this requires another round-trip. Not a good solution. – Lucky Soni Apr 09 '16 at 21:52
  • 1
    @LuckySoni Added shared route handler method that gets rid of the redirect if that is what's desired. – mekwall Apr 11 '16 at 13:40
  • Still feels hacky. This answer here http://stackoverflow.com/questions/15350025/express-js-single-routing-handler-for-multiple-routes-in-a-single-line as mentioned by @TMPilot looks clean. – Lucky Soni Apr 13 '16 at 09:16
  • 1
    @LuckySoni Hacky? Just different solutions to solve the problem.I prefer defining separate routes due to readability but I added the combined route definition as well. Happy now? – mekwall Apr 13 '16 at 15:43
  • @MarcusEkwall Thank you for updating the answer and making it more useful. Removed downvote. – Lucky Soni Apr 16 '16 at 21:14
  • @LuckySoni another round trip - yes, but from the SEO perspective this is the best because search engine will know which url to finally index and most importantly will not split relevance rating between two (or more) pages. – Dmitriy Dec 19 '18 at 18:58