【发布时间】:2021-01-02 15:01:41
【问题描述】:
为了可重用性的目的,我需要获取 URL 的确切路径以在另一个中间件中使用。它应该返回没有将路径参数转换为特定值的url,并且没有查询参数。
例如:如果用户输入https://localhost:3000/path1/4/path2,其中/4在我定义的路径中定义为/:id,那么提取的路径应该是/path1/:id/path2。
到目前为止,我发现的唯一有用的方法是:
- 使用
req.originalUrl=> 将返回/path1/4/path2 - 使用
req.baseUrl + req.path=> 也会返回/path/4/path2,同上 - 使用
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