node.js - 最小化重复路由 index.js
问题描述
我正在尝试使用包含嵌套子路由的快速路由器构建 REST API。我已经在我的index.js
文件中安装了这些子路由。
我将其定义如下:
// Mounted routes
app.use('/api/v1/Project', new ProjectRouter().routes);
app.use('/api/v1/Project/:projectId/Context', new ContextRouter().routes);
app.use('/api/v1/Project/:projectId/Context/:contextId/Question', new QuestionRouter().routes);
app.use('/api/v1/Project/:projectId/Context/:contextId/Question/:questionId/Answer', new AnswerRouter().routes);
我想围绕功能安排我的路线,并且更多地抱怨 REST 标准。
在上述情况下,路由前缀
/api/v1/Project/
会一遍又一遍地重复。是否有一些最佳实践可以通过前缀最小化冗余路由?
解决方案
我通过使用Express.JS 中的嵌套路由器链接中详述的方法解决了我的问题。
解决方案是我们只需将嵌套路由器安装在模块中,如下所示:
app.use('/:nestedId/nestedRoute', nestedRouter);
此外,我们还需要合并父路由参数,我们可以通过将options
对象传递给express.Router
方法来做到这一点:
const router = express.Router({ mergeParams: true });
推荐阅读
- javascript - Angular 7 Guard 重定向仅适用于双击
- angular - 特殊字符不应该允许在反应形式中的第一个字符 - Angular 7
- python - Project Euler #25 - 性能可以进一步提高吗?
- javascript - 如何从 localhost php 文件中的“$.post”获取数据?
- javascript - 将函数作为参数传递给函数
- c# - 初始化基类中的所有派生成员变量是不是一个坏主意?
- html - 相对容器位置错误
- kubernetes - How to access external SMTP server from within Kubernetes cluster with Istio Service Mesh
- excel - 如果单元格包含特定文本,则删除 Outlook 约会
- java - TimeZone.getTimeZone("PST") 与 TimeZone.getTimeZone("America/Los_Angeles")