繁体   English   中英

如何在Express Node.js上提取路由名称(路径)(在通话期间,从请求中)

[英]How can I extract the route name (path) on express nodejs (during the call, from the 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 但是由于您是在请求后执行console#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来获得请求的确切路径,就像上面的代码一样,但是它可以为您提供所使用的确切路径,而不是定义的匹配器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM