简体   繁体   English

节点快递获取路线

[英]node express get route

I need to create express route for the following url: www.somesite.com/some-text-goes-here-id 我需要为以下网址创建快速路由:www.somesite.com/some-text-goes-here-id

In this case i want to have to parameters: text: some-text-goes-here id: id 在这种情况下,我需要输入以下参数:文本:某些文本在此处id:id

Official documentation states the following example: 官方文档陈述以下示例:

Route path: /flights/:from-:to
Request URL: http://localhost:3000/flights/LAX-SFO
req.params: { "from": "LAX", "to": "SFO" }

However in my case i need to have multiple '-' and only the last one should be id ... 但是在我的情况下,我需要有多个“-”,并且只有最后一个应该是id ...

This would be example 这是一个例子

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

Im not sure if this is even possible to do this way? 我不确定是否可以这样做?

Thanks 谢谢

From docs: 从文档:

Since the hyphen (-) and the dot (.) are interpreted literally, they can be used along with route parameters for useful purposes. 由于连字符(-)和点(。)是按字面解释的,因此可以将它们与路由参数一起使用,以达到有用的目的。

So you can write just 所以你可以写

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

that is not possible. 这是不可能的。 You can either have 你可以拥有

 /flights/:from/:to
 then you can have 
 req.params: { "from": "some-text-goes-here", "to": "123" }

or have 或有

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

I think I found out pretty easy way to do it: 我认为我发现了一种非常简单的方法:

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

And if i just want to handle id below goes another route: 如果我只想处理下面的ID,则走另一条路线:

Route path: /site/:id
Request URL: http://localhost:3000/site/123
req.params: { "id": "123" }

Only downside here is that first param is unnamed "0". 唯一的缺点是第一个参数未命名为“ 0”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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