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パスは、ルートパスと正確に一致する必要がありますこの記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加