我使用express + node.js,我有一个req对象,浏览器中的请求是/帐户,但当我日志req. js。我得到'/' -而不是'/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();
    }
  });

要求的事情。路径是/当它应该是/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();
  }
});

要求的事情。路径是/当它应该是/account ??

这样做的原因是Express减去你的处理程序函数挂载的路径,在本例中是'/account'。

他们为什么要这样做?

因为这样可以更容易地重用处理程序函数。您可以为req创建一个处理程序函数来做不同的事情。Path === '/'和req. Path。Path === '/goodbye'例如:

function sendGreeting(req, res, next) {
  res.send(req.path == '/goodbye' ? 'Farewell!' : 'Hello there!')
}

然后你可以将它挂载到多个端点:

app.use('/world', sendGreeting)
app.use('/aliens', sendGreeting)

给:

/world           ==>  Hello there!
/world/goodbye   ==>  Farewell!
/aliens          ==>  Hello there!
/aliens/goodbye  ==>  Farewell!

其他回答

在我自己玩了一会之后,你应该使用:

console.log (req.originalUrl)

下面是一个从文档中扩展的例子,它很好地包装了所有你需要知道的关于在所有情况下使用express访问路径/ url的信息:

app.use('/admin', function (req, res, next) { // GET 'http://www.example.com/admin/new?a=b'
  console.dir(req.originalUrl) // '/admin/new?a=b' (WARNING: beware query string)
  console.dir(req.baseUrl) // '/admin'
  console.dir(req.path) // '/new'
  console.dir(req.baseUrl + req.path) // '/admin/new' (full path without query string)
  next()
})

基于:https://expressjs.com/en/api.html#req.originalUrl

结论:如c1moore’s answer所述,使用:

var fullPath = req.baseUrl + req.path;
//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();
  }
});

要求的事情。路径是/当它应该是/account ??

这样做的原因是Express减去你的处理程序函数挂载的路径,在本例中是'/account'。

他们为什么要这样做?

因为这样可以更容易地重用处理程序函数。您可以为req创建一个处理程序函数来做不同的事情。Path === '/'和req. Path。Path === '/goodbye'例如:

function sendGreeting(req, res, next) {
  res.send(req.path == '/goodbye' ? 'Farewell!' : 'Hello there!')
}

然后你可以将它挂载到多个端点:

app.use('/world', sendGreeting)
app.use('/aliens', sendGreeting)

给:

/world           ==>  Hello there!
/world/goodbye   ==>  Farewell!
/aliens          ==>  Hello there!
/aliens/goodbye  ==>  Farewell!

它应该是:

req.url

快递里

在某些情况下,你应该使用:

req.path

这将为您提供路径,而不是完整的请求URL。例如,如果你只对用户请求的页面感兴趣,而不关心url的所有参数:

/myurl.htm?allkinds&ofparameters=true

要求的事情。Path会给你:

/myurl.html