node.js - 处理在 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”开头
我将如何处理?
解决方案
我会尝试以下方法:
app.use('/articles/:id/comments', commentRoutes);
app.use('/articles', articleRoutes);
所以我认为顺序在上面很重要。
// inside commentRoutes
Router.get('/', (req, res) => {
let articlesId = req.originalUrl.split('/')[2]
})
我希望这有帮助
推荐阅读
- laravel - err_too_many_redirects 和此页面在 laravel 我的中间件中不起作用
- html - 如何为 CSS img 封面设置锚点
- javascript - 滚动时表中的输入字段“保留”同一行中的编辑数字(JSView)
- r - 从不同文件夹导入多个 csv 文件并将文件名提取为附加列:标题和多文件夹案例
- arangodb - Arango特别慢,为什么?
- google-cloud-platform - Google Cloud - 将数据从存储桶下载到实例
- angular - 以编程方式更改 RadDataForm Switch 编辑器的状态
- jquery - Ajax 加载数据,完全打印整个表格,所有 DataTables 功能都不起作用
- node.js - NodeJS spawn `open` 实际上并没有打开文件
- networking - TCP 在后端 FIN、ACK 后仍然传输数据