1. 程式人生 > >Express~使用node原生http模組 及其 使用express框架前後對比

Express~使用node原生http模組 及其 使用express框架前後對比

1.原生寫法

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

瀏覽器

http://localhost:3000/

hello browser

2.使用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

瀏覽器

http://localhost:3000/demo

hello browser

3.express()到底是什麼東西

可以檢視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;
}

匯出express模組的函式

小結:

1.

express框架簡單封裝了node的http模組,因此,express支援node原生的寫法。express的重要意義在於:支援使用中介軟體 + 路由 來開發web伺服器邏輯。

2.

express()就是createApplication()