我想在expressjs中扩充请求对象的原型,但是不清楚这个请求的定义在哪里?我认为它是http.ServerRequest,但我也找不到这个定义。
执行以下操作的正确方法是什么......
http.ServerRequest.prototype.redirect = function(path) { }
答案 0 :(得分:1)
Express使用此模式in 2.*将其实用程序方法添加到http.IncomingMessage.prototype
:
var http = require('http'),
req = http.IncomingMessage.prototype;
req.foo = function(bar) {
// Do cool stuff
};
这种模式in 3.*:
var http = require('http');
var req = exports = module.exports = {
__proto__: http.IncomingMessage.prototype
};
然而,正如Vadim Baryshev在他的回答中警告的那样,小心修补猴子是明智的。
答案 1 :(得分:0)
查看Connect framework和他的middleware libs。每个中间件在创建后扩展请求和响应对象。更改核心对象的原型不是最好的方法,因为这会导致其他模块中出现不可预测的行为。