Reputation: 1109
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
});
Upvotes: 16
Views: 13563
Reputation: 31
Just in case people still stumble upon this ancient post. You can do this now if you just want an alias:
app.get(['/your-route', '/alias1', '/alias2', '/...'], (req, res) => {
// ...
})
Upvotes: 3
Reputation: 28974
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);
Upvotes: 30