node express get route

时间:2016-07-13 12:44:11

标签: node.js express

我需要为以下网址创建快速路由: www.somesite.com/some-text-goes-here-id

在这种情况下我想要参数: text:some-text-goes-here 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" }

我不确定这是否可以这样做?

由于

3 个答案:

答案 0 :(得分:0)

来自docs:

  

由于连字符( - )和点(。)按字面解释,它们   可以与路线参数一起使用以用于有用的目的。

所以你可以写

Route path: /flights/some-text-goes-here-:id
Request URL: http://localhost:3000/flights/some-text-goes-here-123
req.params: { "id": "123" }

答案 1 :(得分:0)

这是不可能的。你可以有

 /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.

答案 2 :(得分:0)

我想我发现了很简单的方法:

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"。

相关问题