2012-07-09 48 views
0

我正在尝试构建一个调试代理,以便在调用各种AP​​I时可以看到请求和响应,但是我坚持要将数据发送到original method在这种情况下,方法克隆会起作用吗?

我怎样才能发送块到原来的方法?

var httpProxy = require('http-proxy'); 

var write2; 

function write (chunk, encoding) { 

    /* 
     error: Object #<Object> has no method '_implicitHeader' 
     because write2 is not a clone. 
    */ 
    //write2(chunk, encoding); 

    if (Buffer.isBuffer(chunk)) { 
     console.log(chunk.toString(encoding)); 
    } 
} 


var server = httpProxy.createServer(function (req, res, proxy) { 

    // copy .write 
    write2 = res.write; 
    // monkey-patch .write 
    res.write = write; 

    proxy.proxyRequest(req, res, { 
     host: req.headers.host, 
     port: 80 
    }); 

}); 

server.listen(8000); 

我的项目是here

回答

0

稍微修改JavaScript: clone a function

Function.prototype.clone = function() { 
    var that = this; 
    var temp = function temporary() { return that.apply(this, arguments); }; 
    for(key in this) { 
     Object.defineProperty(temp,key,{ 
      get: function(){ 
      return that[key]; 
      }, 
      set: function(value){ 
      that[key] = value; 
      } 
     }); 
    } 
    return temp; 
}; 

我已经改变了克隆分配,而使用getter和setter方法,以确保克隆的功能性的任何变化都会反映在克隆的对象上。

现在你可以使用类似于write2 = res.write.clone()的东西。

还有一件事,你可能更希望将此功能从原型分配更改为常规方法(将函数传递给克隆)这可能会使您的设计稍微更清晰。

相关问题