首页 > 解决方案 > 最小化重复路由 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/会一遍又一遍地重复。

是否有一些最佳实践可以通过前缀最小化冗余路由?

标签: node.jsexpress

解决方案


我通过使用Express.JS 中的嵌套路由器链接中详述的方法解决了我的问题。

解决方案是我们只需将嵌套路由器安装在模块中,如下所示:

app.use('/:nestedId/nestedRoute', nestedRouter);

此外,我们还需要合并父路由参数,我们可以通过将options对象传递给express.Router方法来做到这一点:

const router = express.Router({ mergeParams: true });

推荐阅读