我想在node.js的响应和请求中添加新方法。
我怎样才能更有效地做到这一点?
我不明白这是如何在express.js中完成的
作为 JavaScript,有很多方法可以做到这一点。在我看来,对于express来说最合理的模式是将函数添加到早期中间件中的每个请求实例:
//just an example
function getBrowser() {
return this.get('User-Agent');
}
app.use(function (req, res, next) {
req.getBrowser = getBrowser;
next();
});
app.get('/', function (req, res) {
//you can call req.getBrowser() here
});
在express.js中,这是通过向http.IncomingMessage的原型添加附加函数来完成的。
https://github.com/visionmedia/express/blob/5638a4fc624510ad0be27ca2c2a02fcf89c1d334/lib/request.js#L18 https://github.com/visionmedia/express/blob/5638a4fc624510ad0be27ca2c2a02fcf89c1d334/lib/request.js#L18
这有时称为“猴子修补”或“自由修补”。对于这到底是美妙还是糟糕,人们的看法各不相同。我上面的方法更加谨慎,不太可能对 Node.js 进程中运行的其他代码造成故意干扰。添加您自己的:
var http = require('http');
http.IncomingMessage.prototype.getBrowser = getBrowser; //your custom method
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)