如何根据正则表达式指定的路径将路由器附加到 Express 应用程序?

How to attach a router to an express app based on a path specified by a regular expression?

使用这个非常简单的应用程序:

const express = require('express');

const app = express();
const router = express.Router();
const port = 8080;

router.get('/test', (req, res) => {
    res.send('Test was hit')
})

// binds router to express app
app.use('/root', router);

app.listen(port, () => logger.info(`Listening on port: ${port}`));

运行curl http://localhost:8080/root/test之后,不出所料,响应是Test was hit

我要使它更通用,并希望消费者能够访问 curl http://localhost:8080/<whatever-the-consumer-specifies>/test 并且仍然访问路由器 /test 端点。

但是,如果我将绑定替换为如下:

app.use('/*',router);

在随后的点击之后,响应是 Cannot GET /root/test

我怎样才能做到这一点?

* 编辑:*

当然可以:

router.get('*/test', (req, res) => {
    res.send('Test was hit')
})

但是 - 这不是我寻求的答案,我只想在项目中进行一次此配置。

Express 允许在文档 here.

中提到的路由器中间件中使用正则表达式
app.use(/\/\w+/, router);

您可以替换字符串并在第一个参数中放置一个正则表达式。