你会如何将东西传递给路由器?

How would you pass something to a router?

我一直在开发端点,但我希望它像 bot/:id/vote

一样工作

我怎样才能让 ID 传递到那个路由器,所以它就像 https://example.com/bot/512333785338216465/vote

代码

const vote = require("../routers/voting");
app.use("/bot/:id/vote", vote);

创建新路由器对象时需要使用mergeParams(default: false)选项。

Preserve the req.params values from the parent router. If the parent and the child have conflicting param names, the child’s value take precedence.

所以工作代码是:

const express = require('express');
const app = express();
const { Router } = express;

const vote = Router({ mergeParams: true });
vote.get('/', (req, res) => {
  console.log(req.params); //=> { id: '512333785338216465' }
  res.sendStatus(200);
});

app.use('/bot/:id/vote', vote);

app.listen(3000, () => console.log('Server started at http://localhost:3000'));

包版本:"express": "^4.17.1",