首页 > 解决方案 > restify 中如何支持可选参数?

问题描述

我正在使用 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.jsrestify

解决方案


我认为你不能在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最佳实践,您不应该放置可选的路径参数。它应该在查询参数或非 GET 请求的请求正文中。


推荐阅读