node.js - 如何修复快速路由的空结果?
问题描述
我在快车上的一条路线遇到一个问题,当我尝试从一个带有 URL 的参数中搜索数据时,我得到一个空响应。
路由器:
router.get('/:ownerId', (req, res) => {
const ownerId = req.params.ownerId;
res.json({ ownerId: ownerId });
});
整个网址将是http://localhost:3000/bots/:ownerId
.
我试图通过 req.query 发出请求,并且发生了同样的问题。 该路线与其他两条路线在同一个文件中(我认为这没有任何意义)。
所有机器人都获取文件:
// List all bots on database | WORKING
router.get('/', async (req, res) => {
const Model = await Bot.find();
if(Model.length === 0) {
res.json({ Error: 'This collection are empty.' });
} else {
res.json(Model);
}
});
// Find bots by their names | WORKING
router.get('/:name', async (req, res) => {
const botName = req.params.name;
try {
const Model = await Bot.findOne({ name: botName });
res.json(Model);
} catch (err) {
res.json({ Error: 'This bot does not exists.' });
}
});
// Find bots by their ownerId | NOT WORKING
router.get('/:ownerId', (req, res) => {
const ownerId = req.params.ownerId;
res.json({ ownerId: ownerId });
});
解决方案
路线/:name
和/:ownerId
是相同的。如果您使用 URL http://localhost:3000/bots/123
,那么您无法说出 123 是什么 - 它是机器人的名称还是所有者 ID。您定义这些路由的方式所有此类请求都将由第一个处理程序处理,即由/:name
.
您应该以某种方式区分这两条路线。或者,您可以将所有 3 个与两个可选查询参数组合成一个路由:
http://localhost:3000/bots?name=123&ownerId=111 // gets bots with name=123 and with ownerId=111
http://localhost:3000/bots?ownerId=111
http://localhost:3000/bots?name=123
http://localhost:3000/bots // gets all bots without conditions
推荐阅读
- python - opencv BGR 图像与其反向版本 RGB 图像[:,:,::-1] 有什么区别?
- laravel - 如何在 Laravel 的 crudbooster 方法中添加连接查询
- visual-foxpro - 是否可以重叠在 FoxPro 中制作的 GUI?
- python - 人性化不适用于模板中的浮动
- php - WP Image Upload 无法正常工作并添加新插件搜索加载无休止,如何解决?
- java - 如何在informix数据库中使用spring?
- multithreading - 这会导致类似于优先级倒置的问题吗
- java - 需要在 groovy 脚本中给出主文件夹目录路径
- angular - 如何在 Angular 中对异步/同步函数进行排队?
- typescript - 在打字稿中查找旧字符串和新字符串之间的差异