如何修复来自快速路由的空结果



我在快车上的一条路线上遇到了一个问题,当我试图从一个带有URL的参数中搜索数据时,我得到了一个空响应。

路由器:

router.get('/:ownerId', (req, res) => {
const ownerId = req.params.ownerId;
res.json({ ownerId: ownerId });
});

整个url将是http://localhost:3000/bots/:ownerId

我试图通过req.query发出请求,但同样的问题也发生了该路由与另外两个路由在同一个文件中(我认为这没有任何意义(。

文件上的所有机器人GET

// 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相同。如果你使用URLhttp://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

我很确定您经过了/:name路由,因为对于express,无法区分/:ownerId和/:name。由于顺序很重要,您可以切换/:name和/:ownerId路由声明来检查这种行为。

但对于您的主要问题,可能是您可以添加一个字符串模式来区分/:name和/:ownerId(https://expressjs.com/en/guide/routing.html)

最新更新