原生http模块与使用express框架对比

node的http创建服务与利用Express框架有何不同

原生http模块与使用express框架对比:
const http = require("http");

let server = http.createServer(function (req, res) {
 
    
    // 服务器收到浏览器web请求后,打印一句话

        console.log("recv req from browser");

 
        // 服务器给浏览器回应消息
 
       res.end("hello browser");

});
 

server.listen(3000);
服务器执行:
$ node app.js
recv req from browser


使用express框架后:
const http = require("http");

const express = require("express");
 

// app是一个函数

let app = express();
 

http.createServer(app);
 

// 路由处理,默认是get请求

app.get("/demo", function(req, res) {
    
    console.log("rcv msg from browser");

        res.send("hello browser");
    
    res.end();

});
 

app.listen(3000);
服务器执行:
$ node app.js
rcv msg from browser


express到底是什么?
function createApplication() {
    
    var app = function (req, res, next) {
        
        app.handle(req, res, next);
   
     };
 
    
    mixin(app, EventEmitter.prototype, false);
    
    mixin(app, proto, false);
 
    
    // expose the prototype that will get set on requests
    
    app.request = Object.create(req, {
        
        app: { configurable: true, enumerable: true, writable: true, value: app }
    
    })
 
    
    // expose the prototype that will get set on responses
    
    app.response = Object.create(res, {
        
        app: { configurable: true, enumerable: true, writable: true, value: app }
    
    })
 
    
    app.init();
    
    return app;

}

总结:
1.express框架简单封装了node的http模块,因此,express支持node原生的写法。express的重要意义在于:支持使用中间件 + 路由 来开发web服务器逻辑。
2.express()就是createApplication()

 

略。

posted @ 2019-02-15 18:26  仔行天下  阅读(1991)  评论(0编辑  收藏  举报