【问题标题】:How to support optional parameters in restify?restify 中如何支持可选参数?
【发布时间】:2020-01-01 08:00:34
【问题描述】:

我正在使用 Restify 创建 REST API。我以 /ConfigDetails/:name/:id 格式创建了路由,其中​​ name 和 id 是可选的。

If none of the two params is given, all configdetails will be fetched;
If name is given, config details for that name will be returned;
If id is given, config details for that id will be returned;

我的问题是,如何使它们成为可选的?使用我定义的当前路由,除非所有两个参数都存在,否则它将无法解析并会落入默认路由。 根据我的理解,restify 不支持“?” 谁能帮我解决这个问题。

【问题讨论】:

    标签: node.js restify


    【解决方案1】:

    我认为你不能在 restify 中这样做。我有一个工作可以为你工作。

      router.get('/ConfigDetails/:name/:id', handler)
      router.get('/ConfigDetails/:name', handler)
      router.get('/ConfigDetails', handler)
    
    
      function handler(req, res, next) {
         const {name = '', id = ''} = req.params
         // your code here
      }
    

    对于 REST API best practices,您不应该放置可选的路径参数。它应该在查询参数或非 GET 请求的请求正文中。

    【讨论】:

      猜你喜欢
      • 2012-12-29
      • 1970-01-01
      • 2012-02-29
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 2012-03-20
      相关资源
      最近更新 更多