首页 > 解决方案 > 如何修复快速路由的空结果?

问题描述

我在快车上的一条路线遇到一个问题,当我尝试从一个带有 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 });
});

标签: node.jsexpressrouter

解决方案


路线/: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

推荐阅读