我正在使用 express nodejs 來訪問端點:
app.use("/number", numberRouter);
現在我必須處理路徑不同的 URL。在這里,我們在同一個 URL 中有三個不同的路徑:
- https://localhost:8080/number/one
- https://localhost:8080/number/二
- https://localhost:8080/number/三
處理 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)。這可能嗎?
我正在使用郵遞員進行測驗,如果我使用以下 URL 發送發布請求:
localhost:8080/number/one發布請求失敗。我想要在代碼中這樣的東西:
numberRouter.post("/variablePath", async (req:Request, res:Response) => { ... }
其中variablePath是通過郵遞員 ( 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
}
});
通過郵遞員的發帖請求:localhost:8080/number/:pathNum。在郵遞員中設定標題pathNum下Params部分的值。Path Variables

uj5u.com熱心網友回復:
使用路由引數
例如,將您的引數添加到路由器,/: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
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/464818.html
