Node.js Express-使用查询参数获取请求路径

Node.js Express-使用查询参数获取请求路径,node.js,express,Node.js,Express,目前,我有一个公开这两个端点的服务 app.get('/test/', (req, res) => { res.send('hello world'); }); app.get('/test/:id', (req, res) => { res.send('hello world'); }); 我有一个中间件,它记录到这些端点的所有请求。 如果第二个端点被击中,我想记录/test/:id,而不是/test/implexid 如何以这种方式从req对象提取路由?这将帮

目前,我有一个公开这两个端点的服务

app.get('/test/', (req, res) => {
    res.send('hello world');
});

app.get('/test/:id', (req, res) => {
    res.send('hello world');
});
我有一个中间件,它记录到这些端点的所有请求。 如果第二个端点被击中,我想记录
/test/:id
,而不是
/test/implexid

如何以这种方式从
req
对象提取路由?

这将帮助您

app.get('/test/:id', (req, res) => {
   let actualId = req.query.id;
   let reqPath = req.originalUrl || req.path 
   res.send('hello world :', actualId);
});

使用
request.route.path
,它将输出您提供的路径字符串:

app.get('/test/', (req, res) => {
    console.log(req.route.path)
    // -> /test/
    res.send('hello world');
});

app.get('/test/:id', (req, res) => {
    console.log(req.route.path)
    // -> /test/:id
    res.send('hello world');
});

您应该能够通过:
req.route.path
访问路由,但我不确定这是否在中间件中起作用。请确认,
req.route.path
在中间件中起作用。至少在express 4中是这样。*所以,@RolandStarke我想你可以把它作为一个答案发布出来。@RolandStarke只有在端点被击中后才有效。在端点之前调用的中间件中,我如何获得该值?恐怕您不能。但我想你可以注册一个事件监听器或monkey patch某种方法,在它被填充后读取
req.route.path