208

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

4

9 回答 9

297

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

console.log(req.originalUrl)

于 2012-09-21T08:51:04.213 回答
78

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

req.path

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

/myurl.htm?allkinds&ofparameters=true

req.path 会给你:

/myurl.html
于 2013-05-19T11:17:33.537 回答
67

作为补充,这里是一个从文档扩展的示例,它很好地包含了您在所有情况下使用 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 的回答所说,使用:

var fullPath = req.baseUrl + req.path;
于 2019-05-30T15:12:18.013 回答
14

8 年后更新:

req.path已经在做我在这里提到的完全相同的事情。我不记得这个答案如何解决问题并被接受为正确答案,但目前它不是有效答案。请忽略这个答案。感谢@mhodges 提到这一点。

原答案:

如果您想真正获得没有查询字符串的“路径”,您可以使用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();
    }
});
于 2013-06-19T08:08:26.527 回答
12

它应该是:

req.url

表达 3.1.x

于 2013-04-22T01:38:12.480 回答
11
//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 ??

原因是 Express 减去了您的处理程序函数的挂载路径,'/account'在这种情况下。

他们为什么这样做呢?

因为它更容易重用处理函数。您可以创建一个处理函数来执行不同的操作req.path === '/'req.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!
于 2016-10-03T08:13:37.940 回答
11

对于 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();
  }
});
于 2017-06-27T19:14:47.677 回答
6

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
于 2016-08-17T22:45:21.710 回答
4

1.直接从主文件(app.js / index.js)调用:

app.get('/admin/:foo/:bar/:baz', async (req, res) => {
    console.log(req.originalUrl);
    console.log(req.url);
    console.log(req.path);
    console.log(req.route.path);
    console.log(req.baseUrl);
    console.log(req.hostname);
    console.log(req.headers.host) // OR req.header('host'));
    console.log(req.protocol);

    res.sendStatus(200);
});

接口调用:

http://localhost:3000/admin/a/b/c

输出

/admin/a/b/c (originalUrl)
/admin/a/b/c (url)
/admin/a/b/c (path)
/admin/:foo/:bar/:baz (route.path) (baseUrl)
(
localhost hostname)
localhost:3000 (headers.host (hostname with port number))
http (protocol)


2.从模块调用:

应用程序.js

const express = require('express');
const app = express();

...

const users = require('./users');
app.use('/api/users', users);

用户.js

const express = require('express');
const router = express.Router();

...

router.get('/admin/:foo/:bar/:baz', async (req, res) => {
    console.log(req.originalUrl);
    console.log(req.url);
    console.log(req.path);
    console.log(req.route.path);
    console.log(req.baseUrl);
    console.log(req.hostname);
    console.log(req.headers.host) // OR req.header('host'));
    console.log(req.protocol);

    res.sendStatus(200);
});

接口调用:

http://localhost:3000/admin/a/b/c

输出

/api/users/admin/a/b/c (originalUrl)
/admin/a/b/c (url)
/admin/a/b/c (path)
/admin/:foo/:bar/:baz (route.path) (baseUrl)
/api/users (
localhost hostname)
localhost:3000 (headers.host (hostname with port number))
http (protocol)

于 2021-10-20T14:15:03.710 回答