繁体   English   中英

了解expressjs基本代码

[英]understanding expressjs base code

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

相关代码:

express.js上,此代码:

app.request = { __proto__: req, app: app };
app.response = { __proto__: res, app: app };

注意__proto__已过时。 @Bergi告诉我 ,我可以将以下代码替换为:

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.jsresponse.js也具有继承性,这似乎是可以理解的,尽管我并不完全了解它们的工作方式。

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

我对javascript不太满意。 我想找一些关于继承的书。

我的问题:

  • 所有这些继承的意义是什么。
  • 我指出的第一种和第二种情况不是多余的吗?
  • 我应该如何重写以避免过时的__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所做的事情?)

这种方法天生没有错:

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

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

就个人而言,如果它是一个静态函数,没有做任何花哨的事情,我会将其存储在一个单独的模块中,在require()地方将它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();
});

一个人为的,虽然没有用的示例,但在某些情况下可能很有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM