[英]node express get route
我需要為以下網址創建快速路由:www.somesite.com/some-text-goes-here-id
在這種情況下,我需要輸入以下參數:文本:某些文本在此處id:id
官方文檔陳述以下示例:
Route path: /flights/:from-:to
Request URL: http://localhost:3000/flights/LAX-SFO
req.params: { "from": "LAX", "to": "SFO" }
但是在我的情況下,我需要有多個“-”,並且只有最后一個應該是id ...
這是一個例子
Route path: /flights/???
Request URL: http://localhost:3000/flights/some-text-goes-here-123
req.params: { "from": "some-text-goes-here", "to": "123" }
我不確定是否可以這樣做?
謝謝
從文檔:
由於連字符(-)和點(。)是按字面解釋的,因此可以將它們與路由參數一起使用,以達到有用的目的。
所以你可以寫
Route path: /flights/some-text-goes-here-:id
Request URL: http://localhost:3000/flights/some-text-goes-here-123
req.params: { "id": "123" }
這是不可能的。 你可以擁有
/flights/:from/:to
then you can have
req.params: { "from": "some-text-goes-here", "to": "123" }
或有
/flights/:from-to-dest
then you can have
req.params: { "from-to-dest": "some-text-goes-to-123" }
and then split the text by delimiter -to- and take 2nd token
or split just by - and take last token.
我認為我發現了一種非常簡單的方法:
Route path: /site/*-:id
Request URL: http://localhost:3000/site/some-text-goes-here-123
req.params: { "0": "some-text-goes-here", "id": "123" }
如果我只想處理下面的ID,則走另一條路線:
Route path: /site/:id
Request URL: http://localhost:3000/site/123
req.params: { "id": "123" }
唯一的缺點是第一個參數未命名為“ 0”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.