• 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:UsersadminWebstormProjectslearning-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:UsersadminWebstormProjectslearning-express-step5>node learning-express-step5.js
    var log = 1
    1
    2
    var log = 2
    1
    2
    var log = 3
    1
    2
  • 相关阅读:
    ubuntu下文件安装与卸载
    webkit中的JavaScriptCore部分
    ubuntu 显示文件夹中的隐藏文件
    C语言中的fscanf函数
    test
    Use SandCastle to generate help document automatically.
    XElement Getting OuterXML and InnerXML
    XUACompatible meta 用法
    Adobe Dreamweaver CS5.5 中文版 下载 注册码
    The Difference Between jQuery’s .bind(), .live(), and .delegate()
  • 原文地址:https://www.cnblogs.com/lianghong881018/p/11010683.html
Copyright © 2020-2023  润新知