learning express middleware
var express = require('express');var app = express();var log = 0var myLogger = function (req, res, next) { log++; console.log('var log =', log); next();};app.use(myLogger);app.get('/', function(req, res){ res.send("hello world");});app.listen(3000);
result:
C:\Users\admin\WebstormProjects\learning-express-step5>node learning-express-step5.jsvar log = 1var log = 2var log = 3var log = 4
request time log:
var express = require('express');var app = express();var log = 0var myLogger = function (req, res, next) { log++; console.log('var log =', log); next();};var requestTime = function(req, res, next){ req.requestTime = Date.now(); next();}app.use(myLogger);app.use(requestTime);app.get('/', function(req, res){ //res.send("hello world"); var responseText = 'hello world!'; responseText +='Requested at: ' + req.requestTime + '' res.send(responseText);});
result:
write middleware
var express = require('express');var app = express();var mw = require('./my-middleware');var log = 0;var myLogger = function (req, res, next) { log++; console.log('var log =', log); next();};var requestTime = function(req, res, next){ req.requestTime = Date.now(); next();}app.use(myLogger);app.use(requestTime);app.use(mw({option1:'1',option2:'2'}));app.get('/', function(req, res){ //res.send("hello world"); var responseText = 'hello world!'; responseText +='Requested at: ' + req.requestTime + '' res.send(responseText);});app.listen(3000);
my-middleware.js each request print log option1 and option2
module.exports = function (options) { return function (req, res, next) { console.log(options.option1); console.log(options.option2); next() }
result:
C:\Users\admin\WebstormProjects\learning-express-step5>node learning-express-step5.jsvar log = 112var log = 212var log = 312