【问题标题】:Modify Gzipped HTML response from node-http-proxy修改来自 node-http-proxy 的 Gzipped HTML 响应
【发布时间】: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();
        });
    });
});

有什么想法吗?

【问题讨论】:

    标签: php html node.js proxy


    【解决方案1】:

    我已经解决了这个问题。

    无法上传源代码,但我可以给你一些提示。

    1. 使用 server.proxy.on("proxyResponse" 检查内容编码
    2. 除了在 r​​es.write 上收集块之外什么都不做
    3. 在 res.end 上,zlib.unzip 收集块,如果内容编码是“gzip”然后 oldWrite.call(res,decoded_string), oldEnd.apply(res,arguments)
    4. 如果您想更改某些内容,请在 #3 时进行

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2014-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-27
      • 1970-01-01
      相关资源
      最近更新 更多