微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

 

略。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐