What is middleware?
Middleware is any number of functions that are invoked by the Express.js routing layer before your final request handler is, and thus sits in the middle between a raw request and the final intended route. We often refer to these functions as the middleware stack since they are always invoked in the order they are added.
var app = express();
app.get('/', function(req, res) {
res.send('Hello World!');
});
app.get('/info', function(req, res) {
res.send('data');
});
Request-response lifecycle through a middleware is as follows:
The first middleware function (A) in the pipeline will be invoked to process the request
Each middleware function may end the request by sending response to client or invoke the next middleware function (B) by calling next() or hand over the request to an error-handling middleware by calling next(err) with an error argument
Each middleware function receives input as the result of previous middleware function
If the request reaches the last middleware in the pipeline, we can assume a 404 error
app.use((req, res) => {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end("Cannot " + req.method.toUpperCase() + " " + req.url);
});
This pattern has some benefits:
- Avoid coupling the sender of a request to the receiver by giving more than one object a chance to handle the request. Both the receiver and the sender have no explicit knowledge of each other.
- Flexibility in distributing responsibilities among objects. We add or change responsibilities for handling a request by adding to or changing the chain at run-time.