问题描述
出于可重用性的目的,我需要获取URL的确切路径,以便在另一个中间件中使用。它应该返回url,而不将path参数转换为特定值,也不要将query参数转换为
。例如:如果用户输入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
,但不幸的是,当使用快速路由器嵌套路由时,它不起作用,因为它仅返回嵌套路径。 / li>
例如和参考,请看下面的代码片段:
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中的答案,但它们不符合我的确切要求。任何帮助,将不胜感激。谢谢
解决方法
您尝试将req.params与一些js字符串函数一起使用吗? 我不明白您真正需要什么,可以请您分享更多代码+更多详细信息,以便我可以更有效地帮助您,谢谢