【发布时间】:2014-01-18 12:21:30
【问题描述】:
问题:
使用 node-http-proxy 将请求代理到 vagrant box 时,修改 Gzipped HTML 响应会出现白屏。
到目前为止我所拥有的:
我截取请求和修改 html 的方法(见下文)适用于所有非 Gzip 压缩的请求。 (我已经使用 node、ruby、PHP 和 apache 服务器进行了测试)。
令人困惑的部分:
我有一个启动代理并向它发出请求的测试套件。如果我 console.log 响应,我可以清楚地看到 HTML 已被修改 - 只是它根本不会显示在浏览器中......
代理设置
var server = httpProxy.createServer(function (req, res, proxy) {
var next = function () {
proxy.proxyRequest(req, res, {
host: "172.22.22.22",
port: 80,
changeOrigin: true
});
};
var write = res.write;
res.write = function (string, encoding) {
var body = string instanceof Buffer ? string.toString() : string;
body = body.replace(/<\/body>/, function (w) {
return "<script>console.log('injected')</script>\n" + w;
});
if (string instanceof Buffer) {
string = new Buffer(body);
} else {
string = body;
}
write.call(res, string, encoding);
};
next();
}).listen(3002);
// Remove content-length, defaults to 'chunked'
server.proxy.on("proxyResponse", function (req, res, response) {
if (response.headers.hasOwnProperty("content-length")) {
delete response.headers["content-length"];
}
});
我的测试用例显示正确修改的 HTML
it("can modify the html response", function (done) {
var data;
http.get(proxyHost, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk.toString());
});
res.on("end", function () {
data = chunks.join("");
console.log(data); // snippet can be seen in this response
done();
});
});
});
有什么想法吗?
【问题讨论】: