如何使用快速 req 对象获取请求路径

2022-08-30 01:05:29

我使用的是express + node.js我有一个req对象,浏览器中的请求是/account,但是当我记录req.path时,我得到的是'/'---而不是'/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 是 / 当它应该是 /帐户 ??


答案 1

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

console.log(req.originalUrl)


答案 2

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

req.path

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

/myurl.htm?allkinds&ofparameters=true

req.path将为您提供:

/myurl.html