🟢 Node - Middlewares
Updated at 2015-07-25 16:41
Understand what middlewares are and how they should be used. You define a stack of functions that all handle same parameters, change or act based on those parameters and pass them forward to the next function in the stack.
// Example of an Express middleware stack.
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
// Example middleware implementation.
// Middleware could do anything they want with request or response.
var uselessMiddleware = function(request, response, next) {
next();
}
app.use(uselessMiddleware);
// Error in middleware is shown as passing a parameter to next().
// Following middleware simply interrupts every request and jumps forward
// until encounter an error handler.
var worseThanUselessMiddleware = function(request, response, next) {
next('Something bad happened!');
}
app.use(worseThanUselessMiddleware);
// Error handler middleware example.
var logErrorToConsoleMiddleware = function(error, request, response, next) {
if (error) {
console.log(error);
}
next();
};
app.use(logErrorToConsoleMiddleware);