Reputation: 13
app.use(function(req,res,next){ console.log('middleware executed'); next(); });
app.get('/1',function(req,res){ console.log('/1'); res.end(); });
app.get('/2',function(req,res){ console.log('/2'); res.end(); });
...
It works. Middleware executed on both /1 and /2 requests.
Now I want middleware to not be executed on request page /1, but on all pages below:
app.get('/1',function(req,res){ console.log('/1'); res.end(); });
app.use(function(req,res,next){ console.log('middleware executed'); next(); });
app.get('/2',function(req,res){ console.log('/2'); res.end(); });
...
In this case middleware won't execute. Even on request page /2. What's wrong? How to solve this?
Upvotes: 1
Views: 86
Reputation: 203519
The reason is that once you declare a route, Express will (under the hood) insert the router middleware into the middleware chain. This means that any incoming requests will get handled by the router and will (probably) not get passed to any middleware declared after the router/route.
@jgitter's suggestion of including the middleware in the route declaration will work just fine.
Another option is to use app.all
instead of app.use
:
app.get('/1',function(req,res){ console.log('/1'); res.end(); });
app.all('*', function(req,res,next){ console.log('middleware executed'); next(); });
app.get('/2',function(req,res){ console.log('/2'); res.end(); });
Upvotes: 2
Reputation: 3414
That looks correct to me, I'm not sure why it isn't working offhand. As a workaround, you can do this instead:
var middleware = function (req, res, next) {
// do things
next();
};
app.get('/1', middleware, function(req, res) { /* handle request */ });
app.get('/2', function(req, res) { /* handle request */ });
You can also add a mount path as the optional first parameter to the app.use() method.
Upvotes: 1