nodejs express 框架解密3-中间件模块

本文档是基于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 封装响应处理对象。

这就方便后面的视图模板渲染了。

posted @ 2013-12-19 10:51  yupeng  阅读(3351)  评论(0编辑  收藏  举报