node.js - Node js express 路由冲突问题
问题描述
在我的节点 js 应用程序中,我有以下路线。
router.get('/:id', [auth], asyncHandler(async (req, res) => {
const post = await postService.getPostById(req.params.id);
res.json(post);
}));
router.get('/all', [auth], asyncHandler(async (req, res) => {
const posts = await postService.getAllPosts(req.user.id);
res.json(posts);
}));
在这里,当我调用 post/all 路由时,它会崩溃。它说,模型“Post”的路径“_id”的值“all”转换为 ObjectId 失败,模型“Post”的路径“_id”的值“all”转换为 ObjectId 失败
但如果我评论第一条路线,第二条路线完美。为什么会这样?
解决方案
那是因为/all
也匹配/:id
。你需要做的是移到/all
上面/:id
:
// Match this first
router.get('/all', [auth], asyncHandler(async (req, res) => {
const posts = await postService.getAllPosts(req.user.id);
res.json(posts);
}));
// Then if not /all treat route as the variable `id`
router.get('/:id', [auth], asyncHandler(async (req, res) => {
const post = await postService.getPostById(req.params.id);
res.json(post);
}));
推荐阅读
- php - 如何在数组中设置默认值我想设置我的主题默认值
- python - Python-Docx:识别斜体段落
- c# - Http 客户端返回看似编码的数据
- r - 如何在 r markdown 中将表格移动到文本的左侧?
- java - 如何将二进制 XML 插入 Oracle 表?
- python - 将数据帧中的数据与字典中的数据合并
- html - Ipad 上的 Safari Web 扩展对 DOM 操作无响应
- postgresql - 问题:无法访问文件“pg_cron”:没有这样的文件或目录
- javascript - sum 多单元格有一些值应用程序脚本
- docker - docker-compose:“运行时”不支持的配置选项