If you are new to middleware in Express check out the Overview in the Remarks section.
First, we are going to setup a simple Hello World app that will be referenced and added to during the examples.
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.send('Hello World!');
});
app.listen(3000);
Here is a simple middleware function that will log "LOGGED" when it is called.
var myLogger = function (req,res,next) {
console.log('LOGGED');
next();
};
Calling next() invokes the next middleware function in the app.
To load the function call app.use() and specify the function you wish to call. This is done in the following code block that is an extension of the Hello World block.
var express = require('express');
var app = express();
var myLogger = function (req, res, next) {
console.log('LOGGED');
next();
};
app.use(myLogger);
app.get('/', function(req, res) {
res.send('Hello World!');
});
app.listen(3000);
Now every time the app receives a request it prints the message "LOGGED" to the terminal. So, how do we add more specific conditions to when middleware is called? Look at the next example and see.