Content #
Middleware Principles #
Route handlers (app.get, app.post, etc.—often referred to collectively as app.METHOD) can be thought of as middleware that handles only a specific HTTP verb (GET, POST, etc.). Conversely, middleware can be thought of as a route handler that handles all HTTP verbs (this is essentially equivalent to app.all, which handles any HTTP verb; there are some minor differences with exotic verbs such as PURGE, but for the common verbs, the effect is the same).
Route handlers require a path as their first parameter. If you want that path to match any route, simply use \*. Middleware can also take a path as its first parameter, but it is optional (if it is omitted, it will match any path, as if you had specified *).
Route handlers and middleware take a callback function that takes two, three, or four parameters (technically, you could also have zero or one parameters, but there is no sensible use for these forms). If there are two or three parameters, the first two parameters are the request and response objects, and the third parameter is the next function. If there are four parameters, it becomes error-handling middleware, and the first parameter becomes an error object, followed by the request, response, and next objects.
If you don’t call next(), the pipeline will be terminated, and no more route handlers or middleware will be processed. If you don’t call next(), you should send a response to the client (res.send, res.json, res.render, etc.); if you don’t, the client will hang and eventually time out.
If you do call next(), it’s generally inadvisable to send a response to the client. If you do, middleware or route handlers further down the pipeline will be executed, but any client responses they send will be ignored.