从简单例子开始看主函数
express version:4.16.3
从一个简单的例子开始:
var express = require('express') var app = express() app.get('/', function (req, res) { res.send('hello world') }) app.listen(3000)
第一行require('express')引入了express模块。
在express的项目根目录里有一个index.js文件夹,内容是这样:
'use strict';
module.exports = require('./lib/express');
express是从lib/express.js里来的,于是打开lib文件夹下的express.js
exports = module.exports = createApplication; //导出createApplication方法,这就是express模块的核心方法,用于创建一个express应用
然后看一下createApplication这个函数:
function createApplication() { var app = function(req, res, next) { app.handle(req, res, next); }; //新建一个app函数,参数里的req和res是原生的请求和相应对象原型的实例 //这个app函数作为参数被传进http.createServer里,也就是说app.handle()就是处理所有请求的中间件 mixin(app, EventEmitter.prototype, false); //将EventEmitter类的原型上的属性都合并入app中 mixin(app, proto, false); //proto是application.js导出的对象,带有很多属性,将这些属性合并到app上 // expose the prototype that will get set on requests app.request = Object.create(req, { app: { configurable: true, enumerable: true, writable: true, value: app } }) //request属性继承自原生请求对象,http.IncomingMessage.prototype // expose the prototype that will get set on responses app.response = Object.create(res, { app: { configurable: true, enumerable: true, writable: true, value: app } }) //response属性继承自原生响应对象,http.ServerResponse.prototype //上面的request属性和response属性都多加了一个app的数据属性指向app自己 app.init(); //app初始化 return app; //返回app函数 }
当简单例子里运行app.listen(3000)的时候,其实运行的是application.js里给app添加的listen属性:
app.listen = function listen() { var server = http.createServer(this); return server.listen.apply(server, arguments); };
就是创建了服务,然后监听端口。
对比一下原生nodejs的写法:
const http = require('http'); const hostname = '127.0.0.1'; const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World\n'); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });
可以看出给http.createServer传进去的app就是用来处理请求的函数,也就是说express里所有的请求都会经过app这个函数的处理,也就是app.handle(req, res, next);这一句。
所有请求都会经过app.handle()的处理。