Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a route as an alias for another route in Express.js

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
});
like image 403
David Adrian Avatar asked Jan 02 '13 18:01

David Adrian


1 Answers

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);
like image 80
mekwall Avatar answered Sep 18 '22 16:09

mekwall