#
Express Middleware Server Example
This tutorial explains to you how you can use Express.js framework for creating and running middleware functions. This article provides you with an example as well.
In Express applications in particular, in web application in general, it is common to do some logging staff or other things automatically when a web page is called. For instance, you can log the time when the page was requested, the user who create the request, etc.
This kind of tasks are done without a notification and some rules apply.
Here it is an example of Express Middleware Server:
var express = require('express');
var app = express();
var middleOperation1 = function (req, res, next) {
req.requestTime = Date.now()
next()
}
var middleOperation2 = function (req, res, next) {
req.customVariable = "Some data";
next()
}
app.use(middleOperation1)
app.get('/', function (req, res) {
var response = 'ONLY Middleware operation 1 is executed for the main page ! <br>'
response += '<small>This page was requested at: <b><br>' + req.requestTime + '</b></small><br>'
response += 'Here are more information passed by middleware: <b><br>' + req.customVariable + '</b>'
res.send(response)
});
app.use(middleOperation2)
app.get('/test', function (req, res) {
var response = 'Middleware operations 1,2 are executed for the /test page ! <br>'
response += '<small>This page was requested at: <br><b>' + req.requestTime + '</b></small><br>'
response += 'Here are more information passed by middleware: <b><br>' + req.customVariable + '</b>'
res.send(response)
});
app.listen(2000, function () {
console.log('Example app listening on port 2000!');
});
When you run http://localhost:2000 you receive:
When you run http://localhost:2000/test you receive:
Remarks:
- in order to define a middleware staff, it's definition must be done before the routing definition
- in the middleware staff you can add variable to the received request
- the time is not kept in a readable format in Express