![](/img/trans.png)
[英]How express Hapi.js Restfy Koa app.listen() and app.get() work?
[英]How app.listen() and app.get() work on express and hapi
使用http節點模塊(只有本機模塊)我如何重新創建app.listen()和app.get()使用帶有構造函數的http模塊
var app = function(opts) {
this.token= opts.token
}
app.prototype.get = function(callback) {
// use request and response of app.listen()
}
app.prototype.active = function(callback) {
// use request and response of app.listen()
// return on callback some manipulate
//request params
}
app.prototype.listen = function() {
// start http or https server
}
導入模塊並使用它
var app = require(...)
Var client = new app({
token: 0000
})
client.get(function(error, reply) {})
client.listen()
在Node的http模塊之上構建自己非常簡單的HTTP框架非常容易。 這是我制作的一個實現app.get()
和app.listen()
方法的快速方法,您可以看到它如何成長為更像Express的東西:
'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請求對其進行測試:
$ 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路徑必須與路徑路徑完全匹配
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.