Reputation: 473
Im testing the following lines of code.
router.get('/testAPI', function(req, res, next){
console.log('middleware 1');
next();
}, function(req, res, next) {
console.log('middleware 2');
next();
}, function(req, res){
res.send({ SecretData: 'abc123' });
});
It works as expected. However when trying to add:
console.log('middleware 1');
next('route');
instead in middleware 1 so I can skip middleware 2, I get a 404 error on the route: Cannot GET /api/testAPI
anyone have any suggestions/ideas on why this is happening?
In fact I believe its redirecting to my '/' router rather than my '/api' router, because when I add a default route into my '/' router, I get that route rather than the 404 error.
Upvotes: 2
Views: 1600
Reputation: 203534
The documentation explains:
You can provide multiple callback functions that behave just like middleware, except these callbacks can invoke next('route') to bypass the remaining route callback(s)
In other words, by calling next('route')
you're telling Express to not bother with the rest of the callbacks that you're passing for that route.
This has to do with middleware callbacks and route handler callbacks actually being the same thing, there's no way for Express to know that the last callback you're passing is actually the one that you want to call.
One way to solve this is to split the middleware-part of the route from the routehandling-part of the route:
app.get('/testAPI', function(req, res, next) {
console.log('middleware 1');
next('route');
}, function(req, res, next) {
// skipped...
console.log('middleware 2');
next();
});
app.get('/testAPI', function(req, res) {
res.send({ SecretData: 'abc123' });
});
Upvotes: 6