如何修复快速路线的空结果?

How to fix a null result from express route?

当我尝试使用 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相同。如果你取 URL http://localhost:3000/bots/123 那么你就不能说什么是 123 - 它是机器人的名称还是所有者 ID。 您定义这些路由的方式 all 这样的请求将由第一个处理程序处理,即 /: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)