Suppose you have a simple block of code like this:
app.get('/', function(req, res){
res.send('Hello World');
});
This function has two parameters, req and res, which represent the request and response objects respectively.
On the other hand, there are other functions with a third parameter called next. For example, lets have a look at the following code:
app.get('/users/:id?', function(req, res, next){ // Why do we need next?
var id = req.params.id;
if (id) {
// do something
} else {
next(); // What is this doing?
}
});
I can’t understand what the point of next() is or why its being used. In that example, if id doesn’t exist, what is next actually doing?
It passes control to the next matching route. In the example you give, for instance, you might look up the user in the database if an
idwas given, and assign it toreq.user.Below, you could have a route like:
Since /users/123 will match the route in your example first, that will first check and find user
123; then/userscan do something with the result of that.Route middleware is a more flexible and powerful tool, though, in my opinion, since it doesn’t rely on a particular URI scheme or route ordering. I’d be inclined to model the example shown like this, assuming a
Usersmodel with an asyncfindOne():Being able to control flow like this is pretty handy. You might want to have certain pages only be available to users with an admin flag:
Hope this gave you some inspiration!