Let's create middleware that adds a property called requestTime to the request object.
var requestTime = function (req, res, next) {
req.requestTime = Date.now();
next();
};
Now let's modify the logging function from the previous example to utilize the requestTime middleware.
myLogger = function (req, res, next, requestTime) {
console.log('LOGGED at ' + requestTime);
next();
};
Let's add the middleware to our app:
var express = require('express');
var app = express();
myLogger = function (req, res, next) {
console.log('LOGGED at ' + req.requestTime);
next();
};
var requestTime = function(req, res, next) {
req.requestTime = Date.now();
next();
};
app.use(requestTime);
app.use(myLogger);
app.get('/', function(req, res) {
res.send('Hello World!');
});
app.listen(3000);
Now the app will log the time at which the request was made. This covers the basics of writing and using Express middleware. For more information see Using Express Middleware.
!!!TODO: Create Using Express Middleware Section!!!