Node.js redirection with / without trailing slash

I have javascript that does different things depending on the URL. for this to work, I need to have consistent URIs.

for example, I need users to always be on www.site.com/users/bob/insteadwww.site.com/users/bob

node, unfortunately, does not support this, as it seems.

I tried redirecting with

router.get('/:user', function(req, res) {
    res.redirect('/users/' + req.params.user' + '/');
});

but this just leads to a redirect cycle, as the URL with a slash and without a slash seems to be considered the same.

How can i do this? thanks!

Edit

I want to switch from WITHOUT a slash to Slash. the answers in another question are treated differently. I can not .substr (-1) my URLs

+4
source share
3

, , express-slash. , ,

$ npm install express-slash

app.js.

var slash   = require('express-slash');

app.use(slash()); // set slash middleware

.

router.get('/:user/', function(req, res) {
    // do your stuff
});

, .

+2

, - , :

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
});
+9

, , .

-, (v4 +), .

express.Router({strict: true});

catch-all, , - - (.) - .. .

var url = require('url');
router.all(/^[^.]*[^\/]$/, function(req, res) {
    let u = url.parse(req.originalUrl);
    return res.redirect(301, u.pathname + '/' + (u.search || ''));
});

..

0

Source: https://habr.com/ru/post/1622430/


All Articles