繁体   English   中英

节点快递获取路线

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM