![](/img/trans.png)
[英]Regex expression for node/express route matching: /api/**/1.2345
[英]Pattern/Regex with matching start word on express route
我有以下路線
router.get("/", hello)
我想更改此路由以接受所有以“thn”開頭的請求。 我還需要檢索路徑變量,以便將值存儲在 req.params object 中,參數為“thn”。 例如,此路線的有效請求將是
/thn-xxx, /thnaxxx, ...
在這些情況下,我需要將請求中傳遞的路徑變量存儲在 req.params object 中,參數為“thn”和值:
thn-xxx用於第一個請求, thnaxxx用於第二個請求。
因此,在我的 controller 中,我將調用:
const {thn} = req.params //thn=thn-xxx the first request, thn=thnaxxx for the second request
我怎樣才能做到這一點? 謝謝
/\/(?<param>thn.*)$/g
https://regex101.com/r/6Vyv0U/1
說明:使用上述正則表達式
/thn
開頭的輸入被視為匹配param
,它從比賽中獲取除第一個/
之外的所有內容這應該允許您提到的每個有效請求示例。
router.get("/thn.*", hello)
對於參數,我們必須提供?
在 URL 但 ACC 符合您的要求,這種方式可能會有所幫助。
const url = req.url
const regex = /\/(?<param>thn.*)$/g
const params = {thn: null}
if (regex.test(url)) {
regex.lastIndex = 0
const m = regex.exec(url)
params.thn = m.groups.param
}
console.log(params)
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.