how to get request path with express req object


Question

I'm using express + node.js and I have a req object, the request in the browser is /account but when I log req.path I get '/' --- not '/account'.

  //auth required or redirect
  app.use('/account', function(req, res, next) {
    console.log(req.path);
    if ( !req.session.user ) {
      res.redirect('/login?ref='+req.path);
    } else {
      next();
    }
  });

req.path is / when it should be /account ??

1
124
9/21/2012 7:32:00 AM

Accepted Answer

After having a bit of a play myself, you should use:

console.log(req.originalUrl)

195
11/8/2014 7:34:27 PM

In some cases you should use:

req.path

This gives you the path, instead of the complete requested URL. For example, if you are only interested in which page the user requested and not all kinds of parameters the url:

/myurl.htm?allkinds&ofparameters=true

req.path will give you:

/myurl.html

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon