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
});
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With