1 一个简单的http服务如下:
var http = require('http')
http.createServer(function(req,res){
res.writeHead(200, {'content-type':'text/plain'})
res.end('hello world')
}).listen(3000, '127.0.0.1')
console.log('server running at http://127.0.0.1:3000/')
but
实际应用中,业务还需要做
请求方法、url解析、查询参数解析、cookie解析、表单解析、图片上传等等处理
but
不管这些业务处理有多复杂,只要最终结果返回如下一个函数作为参数,传递给createServer()方法作为request事件的侦听器就可以了。
function(req,res){
// res.end()
}
2 如 koa框架-http服务
const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000); // 等同于 http.createServer(app.callback()).listen(3000);
分析
//Koa构造函数
//application.js
const response = require('./response');
const compose = require('koa-compose');
const context = require('./context');
const request = require('./request');
const Emitter = require('events');
module.exports = class Application extends Emitter { // 继承events模块,可以订阅-发布功能
constructor(options) {
super();
options = options || {};
this.env = options.env || process.env.NODE_ENV || 'development';
this.middleware = []; // 存储中间件函数的数组
this.context = Object.create(context); // 应用的上下文属性 都继承自对应的原型对象
this.request = Object.create(request); // 应用的请求属性
this.response = Object.create(response); // 应用的响应属性
}
// http.createServer封装
listen(...args) {
debug('listen');
const server = http.createServer(this.callback()); // this.callback()返回一个函数传递给createServer
return server.listen(...args);
}
// Return a request handler callback for node's native http server.
callback() {
const fn = compose(this.middleware);
// 订阅错误事件,继承于events模块
if (!this.listenerCount('error')) this.on('error', this.onerror);
// function(req,res) 传递给createServer的request事件侦听器
const handleRequest = (req, res) => {
const ctx = this.createContext(req, res);
return this.handleRequest(ctx, fn);
};
return handleRequest;
}
// 存储中间件函数
use(fn) {
if (typeof fn !== 'function') throw new TypeError('middleware must be a function!');
debug('use %s', fn._name || fn.name || '-');
this.middleware.push(fn);
return this;
}
}