首页 > 解决方案 > 处理在 NodeJS、Express 中以类似方式开始的不同路由

问题描述

我正在创建一个 API,其中包含属于这些文章的文章和评论。

const articleRoutes = require('./api/routes/articles');
const commentRoutes = require('./api/routes/comments');

然后

app.use('/articles', articleRoutes);
app.use('/comments', commentRoutes);

任何以“articles/”开头的东西都会被转发到articleRoutes,任何以“comments/”开头的东西都会被转发到commentRoutes。评论 GET 请求就像

/comments?article=ID_OF_ARTICLE

像这样一切都运行良好。

但是我想将评论路线重组为

/articles/ID_OF_ARTICLE/comments

但是现在它们都以“/articles”开头

我将如何处理?

标签: node.jsapiexpress

解决方案


我会尝试以下方法:

app.use('/articles/:id/comments', commentRoutes);
app.use('/articles', articleRoutes);

所以我认为顺序在上面很重要。

// inside commentRoutes
Router.get('/', (req, res) => {
  let articlesId = req.originalUrl.split('/')[2]
})

我希望这有帮助


推荐阅读