1. 程式人生 > >原生http模塊與使用express框架對比

原生http模塊與使用express框架對比

cti () get請求 rom 服務器 style mit 函數 路由

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

略。

原生http模塊與使用express框架對比