我无法让它工作:
var proxyResponse = function(res) {
return Object.create(res);
};
对此方法返回的对象调用标准响应方法不起作用,例如:
http.createServer(function(req, res) {
res = proxyResponse(res);
res.writeHead(200, {"Content-Type": "text/html"});
res.end("Hallelujah! (Praise the Lord)");
}).listen(8080);
服务器刚挂起。有人可以解释我做错了吗?
答案 0 :(得分:4)
来自MDC:
Object.create(proto [, propertiesObject ])
这创建了一个新对象,其原型是proto,对象本身没有任何定义:
res.foo = function() {
console.log(this);
}
res.foo();
res = proxyResponse(res);
res.foo();
结果:
{ socket:
{ fd: 7,
type: 'tcp4',
allowHalfOpen: true,
_readWatcher:
{ socket: [Circular],
....
{}
那为什么不抛出错误而爆炸呢?除了混乱的属性查找和设置之外,还有一个原因是它不起作用。
当您的新对象引用与旧对象相同的所有对象时,本身>>不是旧对象。
在:https://github.com/ry/node/blob/a0159b4b295f69e5653ef96d88de579746dcfdc8/lib/http.js#L589
if (this.output.length === 0 && this.connection._outgoing[0] === this) {
这样就完成了请求,this
是新对象,但this.connection._outgoing[0]
仍引用了旧对象,因此请求永远不会完成,服务器也会挂起。
我仍然不知道你在这里想要实现什么,因为在这里使用Object.create
是没有意义的,如果你担心在另一个请求的情况下res被覆盖,那就是不是这种情况,因为每个res都是它自己的引用不同对象的变量。