【问题标题】:How to get the exact URL path defined by me in express middleware without path parameter values and query parameters?如何在没有路径参数值和查询参数的情况下在 express 中间件中获取我定义的确切 URL 路径?
【发布时间】:2021-01-02 15:01:41
【问题描述】:

为了可重用性的目的,我需要获取 URL 的确切路径以在另一个中间件中使用。它应该返回没有将路径参数转换为特定值的url,并且没有查询参数。

例如:如果用户输入https://localhost:3000/path1/4/path2,其中/4在我定义的路径中定义为/:id,那么提取的路径应该是/path1/:id/path2

到目前为止,我发现的唯一有用的方法是:

  1. 使用req.originalUrl => 将返回/path1/4/path2
  2. 使用req.baseUrl + req.path => 也会返回/path/4/path2,同上
  3. 使用req.route.path => 实际上会返回所需的输出/path1/:id/path2,但不幸的是,当使用快速路由器嵌套路由时不起作用,因为它只返回嵌套路径。

例如和参考,请看下面的sn-p:

const express = require("express");

const routes = express.Router();
routes.get("/path2", async (req, res, next) => {

    //assuming a URL of "https://localhost:3000/path1/12/path2?someparam=5"
    //desired output: "/path1/:id/path2"

    console.log(req.originalUrl) // returns "/path1/12/path2"
    console.log(req.baseUrl + req.path); // returns "/path1/12/path2"
    console.log(req.route.path); //returns only "/path2"

});

app.use("/path1/:id", routes); //using the router to nest paths makes req.route.path unusable

我参考了this 中的答案,但它们不符合我的确切要求。任何帮助,将不胜感激。谢谢

【问题讨论】:

    标签: javascript node.js express url express-router


    【解决方案1】:

    您尝试过将 req.params 与一些 js 字符串函数一起使用吗? 我不明白您真正需要什么作为回报,请您分享更多代码+更多详细信息,以便我可以更有效地提供帮助,谢谢

    【讨论】:

    • 这应该是一条评论。我正在尝试提取确切的 PATH,而不是 req.params 所做的路径参数。
    • 我不能在帖子上写 cmets,因为它是一个新帐户,没有理由为此给出 -1 我只是要求提供更多详细信息
    • 我不确定您还需要什么详细信息。我也给出了解释预期和实际输出的代码。
    猜你喜欢
    • 2018-03-17
    • 2019-01-24
    • 2019-08-08
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-09
    相关资源
    最近更新 更多