如何在express nodejs上提取路由名称(路径)(在调用期间,从req中提取)



我有nodejs express服务器,包含一个通用中间件。在那里,我想知道路线名称。例如:

app.use(function (req, res, next) {
//using some npm pkg allowing me to run function after res.status was sent. This code runs at the very end of the request (after the response)
onHeaders(res, function () {
//console #1
console.log(req.route.path); }) 
next(); 
});

app.use((req, res, next) => {
//This code will run before the handler of the api, at the beginning of the request 
//console #2
console.log(req.route.path);
});

app.post('/chnagePass/:id', handeler...) //etc

因此,控制台#1在请求结束时打印/chnagePass/:id。控制台#2不工作,req.route在这一点上是未定义的。

但我想在控制台#2上获得这个路径名(在我的情况下,根据路由的名称,我可以决定一些配置的超时时间(。

在这一点上,我如何获得路线名称(例如/chnagePass/:id(?有可能吗?

非常感谢!

req.route仅为具有路由的中间件填充。但是,由于您在请求之后执行控制台#1,我相信req对象那时已经发生了变化。

我能够用这个代码重现你所看到的

const express = require("express");
const app = express();
app.use(function(req, res, next) {
setTimeout(function() {
console.log("1: " + JSON.stringify(req.route));
}, 2000);
next();
});
app.use(function(req, res, next) {
console.log("2: Route: " + JSON.stringify(req.route));
console.log("2: Path: " + req.originalUrl);
next();
});
app.get("/magic/:id", function(req, res) {
console.log("3: " + JSON.stringify(req.route));
res.send("Houdini " + req.params.id);
});
app.listen(3300, function() {
console.log("Server UP!");
});

您仍然可以通过访问req.originalUrl来获得请求的确切路径,就像上面的代码一样,但这会为您提供所使用的确切路径而不是定义的匹配器。

最新更新