node.js - 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 不支持“?” 谁可以帮我这个事。
解决方案
我认为你不能在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 请求的请求正文中。
推荐阅读
- php - Symfony 5 - 同一页面上的多个表单
- sql - 如何在delphi中接收光标并显示详细信息
- node.js - 使用 puppeteer 抓取网页
- express - 我可以使用 Promise 作为中间件来处理这样的错误吗?
- logstash - 在 logstash.conf 中搜索文件的通配符
- python - 将多级 xml 连同节点的绝对路径作为列名提取到 pandas 数据框中
- python - 编写 Python 时在 VSCode 中使用制表符而不是空格?
- python - 无法为形状为 (129213603, 28) 且数据类型为 int8 的数组分配 3.37 GiB
- visual-studio - Visual Code Windows环境变量路径,如何更正?
- python - 如何从后台进程运行 Python?