zoukankan      html  css  js  c++  java
  • 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 封装响应处理对象。

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

  • 相关阅读:
    菜根谭#245
    菜根谭#244
    菜根谭#243
    菜根谭#242
    菜根谭#241
    菜根谭#240
    菜根谭#239
    菜根谭#238
    菜根谭#237
    [转载]Linux 内核list_head 学习(一)
  • 原文地址:https://www.cnblogs.com/yupeng/p/3481702.html
Copyright © 2011-2022 走看看