Node.js redirect with/without trailing slash
In case someone else is looking for a quick zero dependency solution, this worked fine for me:
app.get('/:page', function(req, res){
// Redirect if no slash at the end
if (!req.url.endsWith('/')) {
res.redirect(301, req.url + '/')
}
// Normal response goes here
});
You can get this by using third-party library which is called express-slash . All you need to do is,
First, install the library
$ npm install express-slash
And, add these to your app.js.
var slash = require('express-slash');
app.use(slash()); // set slash middleware
Then, this is your router.
router.get('/:user/', function(req, res) {
// do your stuff
});
Hope it will be useful for you.