Javascript 如何使用 express req 对象获取请求路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12525928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:37:24  来源:igfitidea点击:

how to get request path with express req object

javascriptnode.jsexpress

提问by chovy

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'.

我正在使用 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 is / when it should be /account ??

req.path 是 / 什么时候应该是 /account ??

回答by Menztrual

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

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

console.log(req.originalUrl)

console.log(req.originalUrl)

回答by DivZero

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:

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

/myurl.htm?allkinds&ofparameters=true

req.path will give you:

req.path 会给你:

/myurl.html

回答by Ciabaros

To supplement, here is an example expanded from the documentation, which nicely wraps all you need to know about accessing the paths/URLs in all cases with express:

作为补充,这里有一个扩展自文档的示例,它很好地包含了在所有情况下使用 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()
})

Based on: https://expressjs.com/en/api.html#req.originalUrl

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

Conclusion:As c1moore's answerstates above, use:

结论:正如上面c1moore 的回答所述,使用:

var fullPath = req.baseUrl + req.path;

回答by Jürgen Paul

It should be:

它应该是:

req.url

req.url

express 3.1.x

快递 3.1.x

回答by Murat ?orlu

If you want to really get only "path" without querystring, you can use urllibrary to parse and get only path part of url.

如果您想真正获得没有查询字符串的“路径”,则可以使用url库来解析并仅获取 url 的路径部分。

var url = require('url');

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

回答by Stijn de Witt

//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 ??

req.path 是 / 什么时候应该是 /account ??

The reason for this is that Express subtracts the path your handler function is mounted on, which is '/account'in this case.

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

Why do they do this?

他们为什么这样做呢?

Because it makes it easier to reuse the handler function. You can make a handler function that does different things for req.path === '/'and req.path === '/goodbye'for example:

因为它可以更容易地重用处理程序函数。你可以做一个处理函数,它为不同的事情req.path === '/'req.path === '/goodbye'例如:

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

Then you can mount it to multiple endpoints:

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

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

Giving:

给予:

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

回答by c1moore

For version 4.x you can now use the req.baseUrlin addition to req.pathto get the full path. For example, the OP would now do something like:

对于 4.x 版,您现在可以使用req.baseUrl除了req.path获取完整路径。例如,OP 现在会执行以下操作:

//auth required or redirect
app.use('/account', function(req, res, next) {
  console.log(req.baseUrl + req.path);  // => /account

  if(!req.session.user) {
    res.redirect('/login?ref=' + encodeURIComponent(req.baseUrl + req.path));  // => /login?ref=%2Faccount
  } else {
    next();
  }
});

回答by Bahman.A

req.route.path is working for me

req.route.path 对我有用

var pool = require('../db');

module.exports.get_plants = function(req, res) {
    // to run a query we can acquire a client from the pool,
    // run a query on the client, and then return the client to the pool
    pool.connect(function(err, client, done) {
        if (err) {
            return console.error('error fetching client from pool', err);
        }
        client.query('SELECT * FROM plants', function(err, result) {
            //call `done()` to release the client back to the pool
            done();
            if (err) {
                return console.error('error running query', err);
            }
            console.log('A call to route: %s', req.route.path + '\nRequest type: ' + req.method.toLowerCase());
            res.json(result);
        });
    });
};

after executing I see the following in the console and I get perfect result in my browser.

执行后,我在控制台中看到以下内容,并且在浏览器中得到了完美的结果。

Express server listening on port 3000 in development mode
A call to route: /plants
Request type: get