使用node-http-proxy访问响应头 [英] Accessing response headers using node-http-proxy
问题描述
我正在尝试借助使用node-http-proxy创建的代理来修改响应. 但是,我无法访问响应头.我想访问响应头,因为我想修改javascript文件并将修改后的javascript文件发送到客户端.
I am trying to modify the response with the help of a proxy created using node-http-proxy. However I am not able to access the response headers. I want to access the response headers since I would like to modify javascript files and send the modified javascript files to the client.
这是我的代码:
var httpProxy = require('http-proxy');
var url = require('url');
var i = 0;
httpProxy.createServer(function(req, res, next) {
var oldwriteHead = res.writeHead;
res.writeHead = function(code, headers) {
oldwriteHead.call(res, code, headers);
console.log(headers); //this is undefined
};
next();
}, function(req, res, proxy) {
var urlObj = url.parse(req.url);
req.headers.host = urlObj.host;
req.url = urlObj.path;
proxy.proxyRequest(req, res, {
host: urlObj.host,
port: 80,
enable: {xforward: true}
});
}).listen(9000, function() {
console.log("Waiting for requests...");
});
推荐答案
writeHead()不一定必须使用标头数组来调用, write()
可以如有必要,还发送标头.
writeHead() doesn't necessarily have to be called with an array of headers, write()
can also send headers if necessary.
如果要访问标头(或设置标头),则可以使用以下命令:
If you want to access headers (or set them), you can use this:
res.writeHead = function() {
// To set:
this.setHeader('your-header', 'your-header-value');
// To read:
console.log('Content-type:', this.getHeader('content-type'));
// Call the original method !!! see text
oldwriteHead.apply(this, arguments);
};
我正在使用apply()
将所有参数传递给旧方法,因为writeHead()
实际上可以有3个参数,而您的代码仅假定有2个.
I'm using apply()
to pass all the arguments to the old method, because writeHead()
can actually have 3 arguments, while your code only assumed there were two.
这篇关于使用node-http-proxy访问响应头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!