原生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()

 

略。

相关文章

根据官网 入门 express
java叫接口control什么的app.get.post等等都是请求方式我们可...
为了前端丢进去的时候可以直接判断中间件就是经过了这个就会...
Express 文件的上传和下载
运行命令下载app.js 增加中间件。
基本模板来的 后面用后就有什么加什么都行。