Node.js Express动态路由的get添加到静态路由中间件堆栈

Node.js Express动态路由的get添加到静态路由中间件堆栈,node.js,express,Node.js,Express,我正在Express中定义静态和动态路由,并且我已经构建了一个通用响应程序来向客户端发送响应。响应者对所有路由都是全局的,因此在最后添加 但是,当我定义静态路由时,匹配的动态路由的中间件会在响应程序之前添加到堆栈中 举例说明: server.get('/hello/test', function(req, res, next) { console.log('/hello/test'); next(); }); server.get('/hello/:page', function

我正在Express中定义静态和动态路由,并且我已经构建了一个通用响应程序来向客户端发送响应。响应者对所有路由都是全局的,因此在最后添加

但是,当我定义静态路由时,匹配的动态路由的中间件会在响应程序之前添加到堆栈中

举例说明:

server.get('/hello/test', function(req, res, next) {
    console.log('/hello/test');
    next();
});
server.get('/hello/:page', function(req, res, next) {
    console.log('/hello/:page');
    next();
});
server.use(function(req, res, next) {
    res.status(200).send('test');
});
在调用响应程序中间件之前,调用curl localhost:3000/hello/test将console.log“/hello/test”和“/hello/:page”。我只想调用第一个匹配的路由中间件


还有什么方法可以防止这种行为吗?

接下来的方法是将控件传递给下一个处理程序。 您只需从路由中删除下一个调用,并将中间件放入函数中即可解决问题:

server.get('/hello/test', myMiddleware(req, res, next), function(req, res) {
    console.log('/hello/test');
});
server.get('/hello/test_b', myMiddleware(req, res, next), function(req, res) {
    console.log('/hello/test_b');
});
server.get('/hello/:page', myMiddleware(req, res, next), function(req, res) {
    console.log('/hello/:page');
});
server.get('*', myMiddleware(req, res, next), function (req, res) {
    res.type('txt').send('Not found');
});


function myMiddleware(req, res, next) {
    console.Log("in midleware")
    next();
}

你有没有试过下一步;从第一条路线开始?->@John如果没有下一个我怎么联系到响应者?