【问题标题】:How can I extract the route name (path) on express nodejs (during the call, from the req)如何在 express nodejs 上提取路由名称(路径)(在通话期间,来自 req)
【发布时间】:2018-10-28 10:32:20
【问题描述】:

我有 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)?有可能吗?

非常感谢!

【问题讨论】:

    标签: javascript node.js express routes


    【解决方案1】:

    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 来获取请求的确切路径,就像上面的代码一样,但这会为您提供使用的确切路径,而不是定义的匹配器。

    【讨论】:

    • 有没有已知的方法可以在没有参数的情况下获取路径?将字符串与端点名称匹配到字符串?
    • 或者您可以建议任何方式,在真正的处理程序之前为应用程序中的每条路线添加处理程序,而不必在每条路线中调用它?
    • 好吧,app.use() 确实在所有其他路由之前运行,假设它是您注册的第一个中间件
    • 但是在 app.use() req.route 上仍然没有填充,对吧?如何在填充后为所有路线分配功能?而不是例如 app.get("/magic/:id", [add_timeout, function(req, res) { res.send(..); }]);和 app.get("/magic2/:id", [add_timeout, function(req, res) { res.send(..); }]);
    • 是的。这将起作用,但您必须确保将该中间件添加到每条路由。来自docsreq.route“包含当前匹配的路由,一个字符串。”。不要认为有其他方法可以得到它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-06
    • 2017-02-15
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    相关资源
    最近更新 更多