【问题标题】:node express get routenode express 获取路由
【发布时间】:2016-07-13 12:44:10
【问题描述】:

我需要为以下网址创建快速路由: www.somesite.com/some-text-goes-here-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" }

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

谢谢

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    来自文档:

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

    所以你可以只写

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

    【讨论】:

      【解决方案2】:

      这是不可能的。你可以有

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

      【讨论】:

        【解决方案3】:

        我想我找到了很简单的方法:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-06-23
          • 2018-07-12
          • 2018-04-23
          • 2018-01-10
          • 1970-01-01
          • 1970-01-01
          • 2022-01-04
          • 2020-03-26
          相关资源
          最近更新 更多