我试图在使用node-http-proxy创建的代理的帮助下修改响应。 但是我无法访问响应标头。我想访问响应标头,因为我想修改javascript文件并将修改后的javascript文件发送到客户端。
这是我的代码:
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...");
});
答案 0 :(得分:2)
writeHead()不一定要使用标头数组调用,write()
也可以在必要时发送标头。
如果要访问标题(或设置标题),可以使用:
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个参数,而你的代码只假设有两个参数。