[英]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.js和response.js也具有繼承性,這似乎是可以理解的,盡管我並不完全了解它們的工作方式。
//is this exporting http.IncomingMessage.prototype???
var req = exports = module.exports = {
__proto__: http.IncomingMessage.prototype
};
我對javascript
不太滿意。 我想找一些關於繼承的書。
我的問題:
__proto__
? 我實際上只是在嘗試編寫一個基於簡單中間件的系統。 我可以做的事情:
// route
app.use('/', function(req,res) {
});
就這么簡單,但是我還想添加更多方法來req
和res
。 這就是為什么我要研究如何實現connect
和express
。 盡管connect
並未向req
和res
添加其他方法。 這就是為什么我試圖理解express
。
將方法添加到res
或req
一種愚蠢的方式是:
// 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.