在到达单个端点时处理不同的 URL 路径 (Nodejs)
Handling different URL paths while hitting a single endpoint (Nodejs)
我正在使用 express nodejs 来访问端点:
app.use("/number", numberRouter);
现在我必须处理路径不同的 URL。这里我们在同一个 URL:
中有三个不同的路径
- https://localhost:8080/number/one
- https://localhost:8080/number/two
- https://localhost:8080/number/three
处理numberRouter的文件:
numberRouter.post("/", async (req:Request, res:Response) => {
var url = req.protocol + '://' + req.get('host') + req.originalUrl;
//what I want to do
if (req.path == "one") {
//do something
}
else if (req.path == "two") {
//do something
}
});
我想要实现的是,一旦我到达 number
端点,我就获取完整的 URL,提取它的 path
并基于 path
我做了进一步的处理,而不是点击三个不同的端点(/number/one
、/number/two
、/number/three
)。
这可能吗?
我正在使用 postman 进行测试,如果我发送带有以下 URL 的 post 请求:
localhost:8080/number/one
post 请求失败。我想要这样的代码:
numberRouter.post("/variablePath", async (req:Request, res:Response) => { ... }
其中variablePath
是通过postman(one
、two
或three
)设置,然后在此处处理。
解决方案(遵循@traynor 的回答):
app.use("/number", numberRouter);
numberRouter.post("/:pathNum", async (req:Request, res:Response) => {
if (req.path === "/one") {
//do something
}
else if (req.path === "/two") {
//do something
}
});
post 请求通过 post 人:localhost:8080/number/:pathNum
。
在 postman 中,在 Path Variables
标题下的 Params
部分中设置 pathNum
的值。
将您的参数添加到路由器,例如 /:myparam
,然后检查它和 运行 您的代码:
numberRouter.post("/:myparam", async (req:Request, res:Response) => {
const myParam = req.params.myparam;
//what I want to do
if (myParam == "one") {
//do something
}
else if (myParam == "two") {
//do something
}
});
我正在使用 express nodejs 来访问端点:
app.use("/number", numberRouter);
现在我必须处理路径不同的 URL。这里我们在同一个 URL:
中有三个不同的路径- https://localhost:8080/number/one
- https://localhost:8080/number/two
- https://localhost:8080/number/three
处理numberRouter的文件:
numberRouter.post("/", async (req:Request, res:Response) => {
var url = req.protocol + '://' + req.get('host') + req.originalUrl;
//what I want to do
if (req.path == "one") {
//do something
}
else if (req.path == "two") {
//do something
}
});
我想要实现的是,一旦我到达 number
端点,我就获取完整的 URL,提取它的 path
并基于 path
我做了进一步的处理,而不是点击三个不同的端点(/number/one
、/number/two
、/number/three
)。
这可能吗?
我正在使用 postman 进行测试,如果我发送带有以下 URL 的 post 请求:
localhost:8080/number/one
post 请求失败。我想要这样的代码:
numberRouter.post("/variablePath", async (req:Request, res:Response) => { ... }
其中variablePath
是通过postman(one
、two
或three
)设置,然后在此处处理。
解决方案(遵循@traynor 的回答):
app.use("/number", numberRouter);
numberRouter.post("/:pathNum", async (req:Request, res:Response) => {
if (req.path === "/one") {
//do something
}
else if (req.path === "/two") {
//do something
}
});
post 请求通过 post 人:localhost:8080/number/:pathNum
。
在 postman 中,在 Path Variables
标题下的 Params
部分中设置 pathNum
的值。
将您的参数添加到路由器,例如 /:myparam
,然后检查它和 运行 您的代码:
numberRouter.post("/:myparam", async (req:Request, res:Response) => {
const myParam = req.params.myparam;
//what I want to do
if (myParam == "one") {
//do something
}
else if (myParam == "two") {
//do something
}
});