我使用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 ??


当前回答

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

req.path

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

/myurl.htm?allkinds&ofparameters=true

要求的事情。Path会给你:

/myurl.html

其他回答

对于版本4。X你现在可以使用请求。除了req之外的baseUrl。获取完整路径。例如,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();
  }
});

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

req.path

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

/myurl.htm?allkinds&ofparameters=true

要求的事情。Path会给你:

/myurl.html

它应该是:

req.url

快递里

对于那些从request .route.path中获得未定义的,这是正确的。

在路由处理器内部,有一个路由。 在中间件处理程序内部,没有路由。

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);
        });
    });
};

执行后,我看到以下在控制台和我得到完美的结果 在我的浏览器里。

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