learning express step(五)

learning  express  middleware

var express = require('express');
var app = express();
var log = 0
var 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.js
var log = 1
var log = 2
var log = 3
var log = 4

 

request time log:

var express = require('express');
var app = express();
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.get('/', function(req, res){
    //res.send("hello world");
    var responseText = 'hello world!<br>';
    responseText +='<small>Requested at: ' + req.requestTime + '</small>'
    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!<br>';
    responseText +='<small>Requested at: ' + req.requestTime + '</small>'
    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.js
var log = 1
1
2
var log = 2
1
2
var log = 3
1
2

 

posted @ 2019-06-12 16:52  嵌入式实操  阅读(119)  评论(0编辑  收藏  举报