Reputation: 2507
In the documentation it says:
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). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there’s no reason to proceed with the current route.
Does this mean that if I write a route like this:
app.get('/', function(req, res, next) {
if (!req.params.id) {
res.statusCode(400).send({error: "id parameter is required"});
next('route');
} else {
next();
}
}, function(req, res) {
res.send({something: 'something'})
});
and params.id
was undefined
, then the next route wouldn't be executed, but if it was present it would?
Basically the coding/naming convention is a little bit confusing me. Why not next(false)
instead of next('route')
?
Upvotes: 4
Views: 1367
Reputation: 2332
(if) params.id was undefined, then the next route wouldn't be executed, but if it was present it would?
Key idea is that the next route in the file would be checked.
From the duplicate question, which answers this in much, much more detail:
next() with no arguments says "just kidding, I don't actual want to handle this". It goes back in and tries to find the next route that would match.
Upvotes: -1
Reputation: 2507
I found the answer. When using app
or the Express router, you can define multiple routes for the same path:
// first set of routes for GET /user/:id
app.get('/user/:id', function (req, res, next) {
// logic
}, function (req, res, next) {
// logic
});
// second set of routes for GET /user/:id
app.get('/user/:id', function (req, res, next) {
// logic
});
If from any of the callbacks (middleware) for the first route, you call next('route')
, all the callbacks for that set of routes will be skipped and control is passed to the next set of routes:
// first set of routes for GET /user/:id
app.get('/user/:id', function (req, res, next) {
next('route')
}, function (req, res, next) {
// this middleware won't be executed at all
});
// second set of routes for GET /user/:id
app.get('/user/:id', function (req, res, next) {
// the next('route') in the first callback of the first set of routes transfer control to here
});
Now using next('route')
rather than next(false)
makes more sense: it transfer control to the next route defined for current path.
Upvotes: 8