Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js redirect with/without trailing slash

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!

edit:

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

like image 429
user3787706 Avatar asked Jan 01 '16 12:01

user3787706


2 Answers

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
});
like image 88
jncraton Avatar answered Sep 19 '22 01:09

jncraton


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.

like image 26
Arkar Aung Avatar answered Sep 20 '22 01:09

Arkar Aung