本文檔是基於express 3.4.6 的
在上篇中我們提到了中間件,這篇主要解釋這個模塊,middleware.js 為:
var utils = require('./utils'); /** * Initialization middleware, exposing the * request and response to eachother, as well * as defaulting the X-Powered-By header field. * * @param {Function} app * @return {Function} * @api private */ exports.init = function(app){ return function expressInit(req, res, next){ if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express'); //將req,res,next 重新封裝下 req.res = res; res.req = req; req.next = next; //將req,res的原型設置為connect的request,response 對象 req.__proto__ = app.request; res.__proto__ = app.response; res.locals = res.locals || utils.locals(res); next(); } };
我們看到這個函數返回一個function,他將我們的app(connect創建的) request ,response 作為了 req,res 的原型對象了。為模板的渲染,直接調用。
那app.request,app.response 是什么呢?
我們看看在express.js中
function createApplication() { var app = connect(); //將application中的方法全部拷貝到connect對象上去。 utils.merge(app, proto); //設置app 的request對象的原型為req,本身的屬性為connect對象 app.request = { __proto__: req, app: app }; //設置app的response對象原型為res ,本身的屬性為connect對象 app.response = { __proto__: res, app: app }; //調用application中的方法init app.init(); return app; }
app.request,app.response 的原型是req,res,他們分別是request.js 封裝的請求處理對象, response.js 封裝響應處理對象。
這就方便后面的視圖模板渲染了。