如何在快速中间件中将所有以字符串 api 开头的调用路由到它们的处理程序

How can I route all calls starting with string api to their handlers in an express middleware

我有一个快递 app.js 典型

app.get('/path1', (req, res => {}) 
app.get('/path2', (req, res => {}) 
app.get('/path3', (req, res => {}) 

现在我想捕获所有路由,从 api 开始,如下所示,并将它们重定向到 express 中相应的处理程序,但不确定如何实现

/api/path1 
/api/path2 
/api/path3 

我假设我可以捕获所有 api 如下

app.all('/api/*', function (request, response, next) { //in a server.js file 
       //how can i call the corresponding paths here?? 
       // looking for something to do forward to current-route.replace('api','') 
       // or something like that 
})

也许 router-level middleware 可以解决您的问题:

const router = express.Router();

router.get('/path1', (req, res => {});
router.get('/path2', (req, res => {});
router.get('/path3', (req, res => {});

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

更新:

使用 redirect(与您当前的解决方案差别不大;未测试):

app.all('/api/*', (request, response) => res.redirect(request.url.replace('/api', '')));

这对我有用,如果有更好的方法请告诉我

app.all('/api/*', function (request, response, next) {
    request.url = request.url.replace('/api','');
    next();  
})