如何使用Express Req对象获取请求路径

JavaScript Node.js

阿飞番长

2020-04-03

我正在使用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是/何时应该是/ account?

第3903篇《如何使用Express Req对象获取请求路径》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
飞云 2020.04.03

自己玩了一些游戏之后,应该使用:

console.log(req.originalUrl)

JinJin 2020.04.03

它应该是:

req.url

快递3.1.x

斯丁 2020.04.03

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

req.path

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

/myurl.htm?allkinds&ofparameters=true

req.path将为您提供:

/myurl.html

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android