理解expressjs基本代码

时间:2014-07-21 15:49:18

标签: javascript node.js express

我正在检查express.js代码并尝试重写它只是为了学习如何创建中间件(框架)。但是代码周围的所有继承都让我感到困惑。

相关代码:

express.js 上显示此代码:

app.request = { __proto__: req, app: app };
app.response = { __proto__: res, app: app };
保持谨慎__proto__已被弃用。 @Bergi told me我可以用以下代码替换此类代码:

app.request = Object.create(req);
app.request.app = app;
app.response = Object.create(res);
app.response.app = app;

但现在奇怪的是, application.js 又有类似的代码 - 我认为

// inherit protos
this.on('mount', function(parent){
  this.request.__proto__ = parent.request;
  this.response.__proto__ = parent.response;
  this.engines.__proto__ = parent.engines;
  this.settings.__proto__ = parent.settings;
});

这里发出的是:

mount_app.mountpath = mount_path;
mount_app.parent = this;

// restore .app property on req and res
router.use(mount_path, function mounted_app(req, res, next) {
  var orig = req.app;
  mount_app.handle(req, res, function(err) {
    req.__proto__ = orig.request;
    res.__proto__ = orig.response;
    next(err);
  });
});

// mounted an app
mount_app.emit('mount', this);

然后即使 request.js response.js 都有继承,这似乎是可以理解的,尽管我并不完全理解他们是如何做到的。< / p>

//is this exporting http.IncomingMessage.prototype???
var req = exports = module.exports = {
  __proto__: http.IncomingMessage.prototype
};

javascript我不是很好。我想找一些关于继承主题的书籍。

我的问题:

  • 所有这些继承的重点是什么。
  • 我指出第1和第2个案件是多余的?
  • 我应该如何重写避免弃用的__proto__

背景

我实际上只是想编写一个简单的基于中间件的系统。我可以做的事情:

// route
app.use('/', function(req,res) {

});

就是这么简单,但我还想向reqres添加更多方法。这就是我正在研究connectexpress如何实现它的原因。虽然connect没有向reqres添加其他方法。这就是我试图理解express的原因。

resreq添加方法的一种简单方法是:

// middleware
app.use(function(req, res) {
   req.mymethod = function()...
});

现在下一个中间件有额外的req方法,但我觉得这很脏。这就是我试图理解expressjs以及它们如何实现继承的原因。

  

注意:我成功编写了一个工作简单的中间件系统,但仍然不知道如何向req / res添加方法。我也在研究对象包装(也许这就是他们对req和res做的事情?)

1 个答案:

答案 0 :(得分:-1)

这种方法没有任何内在错误:

app.use(function(req, res) {
    req.mymethod = function()...
});

中间件按照它定义的顺序运行,只要它出现在你的其他中间件和路由之前,你就可以确保它会在那里。

就个人而言,如果它是一个静态功能,并没有做任何花哨的事情,我会将它存储在一个单独的模块中,require()将它存储在我需要它的地方,然后保留它。但是,如果出于某种原因,您需要特定于请求的变量,那么按照您的建议进行操作可能会很方便。例如,创建一个闭包:

app.use(function(req, res, next) {
    // Keep a reference to `someVar` in a closure
    req.makeMessage = (function(someVar) {
        return function () {
            res.json({hello : someVar});
        };
    })(/* put the var here */);

    next();
});

app.get('/hello', function(req, res) {
    req.makeMessage();
});

一个人为的,相当无用的例子,但它在某些情况下可能有用。

相关问题