0

我想在 expressjs 中增加请求对象的原型,但是不清楚这个请求是在哪里定义的?我认为它是 http.ServerRequest,但我也找不到该定义。

执行以下操作的正确方法是什么...

http.ServerRequest.prototype.redirect = function(path) { }
4

2 回答 2

1

Express 本身将其实用程序方法添加到2.* 中http.IncomingMessage.prototype使用此模式:

var http = require('http'),
    req = http.IncomingMessage.prototype;

req.foo = function(bar) {
  // Do cool stuff
};

而3.* 中的这种模式:

var http = require('http');

var req = exports = module.exports = {
  __proto__: http.IncomingMessage.prototype
};

正如 Vadim Baryshev 在他的回答中警告的那样,谨慎使用猴子补丁是明智的。

于 2012-04-20T23:57:50.033 回答
0

查看Connect 框架和他的中间件库。每个中间件在创建后都会扩展请求和响应对象。更改核心对象的原型并不是最好的方法,因为这会导致其他模块出现不可预测的行为。

于 2012-04-20T20:32:37.033 回答