Node.js 在这种情况下,方法克隆会起作用吗?
我正在尝试构建一个调试代理,以便在调用各种API时可以看到请求和响应,但我在尝试向服务器发送数据时遇到了困难 如何将区块发送到原始方法Node.js 在这种情况下,方法克隆会起作用吗?,node.js,Node.js,我正在尝试构建一个调试代理,以便在调用各种API时可以看到请求和响应,但我在尝试向服务器发送数据时遇到了困难 如何将区块发送到原始方法 var httpProxy = require('http-proxy'); var write2; function write (chunk, encoding) { /* error: Object #<Object> has no method '_implicitHeader' becaus
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);
我的项目是。稍微修改一下
我已将克隆分配更改为使用getter和setter,以确保对克隆函数属性的任何更改都将反映在克隆对象上
现在您可以使用write2=res.write.clone之类的东西
还有一件事,您可能更希望将此函数从原型分配更改为要克隆的函数中的普通方法传递,这可能会使您的设计稍微干净一些
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;
};