使用harmon修改node-http-proxy中的HTML响应 - 无输出操作

时间:2014-04-16 02:23:30

标签: html node.js proxy

可能是一个n00b问题:-)。我正在查看node-http-proxy来创建过滤代理。寻找字符串操作示例,我找到the pointer to harmon并成功运行了example

然后我尝试针对在localhost:80上的Apache HTTP侦听运行我自己的示例。这是我的代码:

    var httpProxy = require('http-proxy');

    // Create an array of selects that harmon will process. 
    var actions = [];

    var simpleaction = {};
    simpleaction.query = 'head';
    simpleaction.func = function (node) {
                             var out = '<style type="text/css"> h1 {color : red; border-bottom : 5px solid green} </style>';
                            node.createWriteStream({ outer: true }).end(out);
                            console.log("head function called:" + out);
                            };
    var simpleaction2 = { 'query' : 'body',
                         'func' : function (node) {
                             var out = '<h1>You have been proxied</h1>';
                            node.createWriteStream({ outer: false }).end(out);
                            console.log("body function called" + out);
                            }
                        };                  

    // Add the action to the action array
    actions.push(simpleaction);
    actions.push(simpleaction2);

    var proxy = httpProxy.createServer(
      require('harmon')([], actions),
      80, 'localhost'
    );

    proxy.listen(8899);

    console.log("Up and running on port 8899");

最初我因为使用​​较新版本的http-proxy而出错。使用0.8.7修复了那个。现在加载页面时的控制台输出是:

stw@devmachine:~/tests$ nodejs ptest.js 
Up and running on port 8899
head function called:<style type="text/css"> h1 {color : red; border-bottom : 5px solid green} </style>
body function called<h1>You have been proxied
head function called:<style type="text/css"> h1 {color : red; border-bottom : 5px solid green} </style>
body function called<h1>You have been proxied
head function called:<style type="text/css"> h1 {color : red; border-bottom : 5px solid green} </style>
body function called<h1>You have been proxied
head function called:<style type="text/css"> h1 {color : red; border-bottom : 5px solid green} </style>
body function called<h1>You have been proxied</h1>

所以它看起来不错,但输出完全没有改变。 我错过了什么?

最终我需要:

  • 将样式表添加到<head>部分
  • 替换所有srchref属性
  • 在特定位置添加一些DOM元素(例如<h1>作为正文的第一个元素)
  • 添加一些标题
  • 发送前GZIP结果
  • 处理http和https网址
  • 单独留下图片资源
指针赞赏!

1 个答案:

答案 0 :(得分:1)

似乎很奇怪 没有完整的测试环境意味着我无法给出明确的答案。 但是我在这里整理了一个POC,它有两个类似于你正在创建的动作。

https://gist.github.com/No9/10874082

如果您从git克隆harmon并将其放入测试文件夹,那该工作正常。

$ git clone https://github.com/No9/harmon.git $ cd harmon/test $ curl https://gist.githubusercontent.com/No9/10874082/raw/38a26d15b7ecbd875eee0988c94af0333927b98a/host-multiaction.js > host-multiaction.js $ node host-multiaction.js

对于GZIP等的整体功能,我会说新版本的node-proxy可以更好地提供完整的解决方案。

我建议在接下来的几周内观看https://github.com/No9/harmon/issues/8;)