在 Node 的 http 模块之上构建您自己的非常简单的 HTTP 框架非常容易。这是我制作的一个快速的实现app.get()
and 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 路径必须与路由路径完全匹配
- 添加路由的顺序很重要(这可能会导致问题)
- 允许冲突的路径
- 缺少很多不错的功能,例如服务文件和渲染模板(尽管您可以在处理程序中手动执行此操作)