I have a javascript that does different things depending on the URL. for that to work, i need to have consistent URIs.
for example, i need users to always be on www.site.com/users/bob/
instead of www.site.com/users/bob
node unfortunately doesn't support that, as it seems.
i tried redirecting with
router.get('/:user', function(req, res) {
res.redirect('/users/' + req.params.user' + '/');
});
but it just results in a redirect loop, as the URL with and without slash seem to be treated as the same.
how can i do this? thanks!
i want to route from WITHOUT slash to WITH slash. the answers in the other question address the other way around. i can't .substr(-1) my URLs
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.
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