简体   繁体   中英

node express get route

I need to create express route for the following url: www.somesite.com/some-text-goes-here-id

In this case i want to have to parameters: text: some-text-goes-here 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 ...

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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