我正在尝试构建一个调试代理,以便在调用各种API时可以看到请求和响应,但我在尝试向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。
发布于 2012-07-10 19:40:06
稍微修改一下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()的内容。
还有一件事,你可能更想把这个函数从一个原型赋值改为一个普通的方法(传入要克隆的函数),这可能会使你的设计稍微干净一些。
https://stackoverflow.com/questions/11402740
复制相似问题