在Node的http模塊之上構建自己的非常簡單的HTTP框架非常簡單。這裏有一個快速的一個我做它實現了app.get()
和app.listen()
方法,你可以看到它如何能成長起來,成爲更多的東西快遞樣:
'use strict';
const Http = require('http');
const Url = require('url');
// Framework
const Framework = function (options) {
this.options = options;
this.routes = [];
this.listener = Http.createServer(this._onRequest.bind(this));
};
Framework.prototype.get = function (path, handler) {
this.routes.push({ path, method: 'GET', handler });
};
Framework.prototype.post = function (path, handler) {
this.routes.push({ path, method: 'POST', handler });
};
Framework.prototype.listen = function (callback) {
this.listener.listen(this.options.port, callback);
};
Framework.prototype._onRequest = function (req, res) {
// Find the first matching route
for (let i = 0; i < this.routes.length; ++i) {
const route = this.routes[i];
const url = Url.parse(req.url);
if (route.method === req.method && url.path === route.path) {
return route.handler(req, res);
}
}
// No matching routes
res.writeHead(404);
res.end('Not found');
};
您可以使用像這樣這臺微型框架:
const app = new Framework({ port: 4000 });
app.get('/', (req, res) => {
res.end('Home page');
});
app.get('/about', (req, res) => {
res.end('About page');
});
app.listen(() => {
console.log('Started server!');
});
您可以用幾個捲曲請求測試:
$ curl -i http://localhost:4000/
HTTP/1.1 200 OK
Date: Sun, 24 Apr 2016 14:38:02 GMT
Connection: keep-alive
Content-Length: 9
Home page
$ curl -i http://localhost:4000/about
HTTP/1.1 200 OK
Date: Sun, 24 Apr 2016 14:38:08 GMT
Connection: keep-alive
Content-Length: 10
About page
$ curl -i http://localhost:4000/spaghetti
HTTP/1.1 404 Not Found
Date: Sun, 24 Apr 2016 14:38:14 GMT
Connection: keep-alive
Transfer-Encoding: chunked
Not found
顯然,這是一個非常基本的框架和許多患有親像hapi這樣的框架已經解決了這個問題:
- 不支持路徑中的參數例如,
/users/{id}
。該URL路徑必須完全
- 你添加路由的順序是非常重要的佈線路徑相匹配(這可能導致問題)
- 衝突的路徑所允許的
- 缺少了很多不錯的功能,如提供文件服務和渲染模板(雖然你可以在處理程序中手動執行此操作)
不確定你在問什麼。你在問如何在Node的核心http模塊之上實現你自己的http框架的一些基本特性? –
@MattHarrison創建相同的表達邏輯創建應用程序並路由並聽取它們。新的應用程序和app.get()app.listen() – user6246965
你看過這些方法的快速源代碼嗎? –