【问题标题】:How do I use node.js http-proxy for logging HTTP traffic in a computer?如何使用 node.js http-proxy 在计算机中记录 HTTP 流量?
【发布时间】:2012-06-14 16:01:33
【问题描述】:

我正在尝试实现最简单的示例:

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

httpProxy.createServer(function (req, res, proxy) {
    //
    // I would add logging here
    //
    proxy.proxyRequest(req, res, { host: 'www.google.com', port: 80 });
}).listen(18000);

当我将浏览器配置为使用此代理并导航到 www.google.com 时,我没有收到任何响应。我做错了什么?

我使用的是 Windows 7 Chrome

【问题讨论】:

  • 你能指定什么操作系统和什么浏览器吗?每个处理代理的方式不同。
  • 库中的最新更改对您有用吗?似乎现在必须在选项中传递target 字段,否则只需运行上面的代码就可以得到Must provide valid URL for target

标签: javascript http node.js http-proxy node-http-proxy


【解决方案1】:

我不确定这是否有帮助,因为发布的信息真的很短。 但我发现他们更新了 api 的帖子...

你可能想看看这篇文章:

更新到 node-http-proxy v0.5.0 http://blog.nodejitsu.com/updating-node-http-proxy

【讨论】:

    【解决方案2】:

    这是一个如何记录请求的简单示例。 我使用类似的方法将我的所有域记录到一个数据库中。

    我从http://blog.nodejitsu.com/http-proxy-middlewares 复制了很多内容(存档)

    var fs = require('fs'),
        http = require('http'),
        httpProxy = require('http-proxy'),
            
    logger = function() {    
      // This will only run once
      var logFile = fs.createWriteStream('./requests.log');
    
      return function (request, response, next) { 
        // This will run on each request.
        logFile.write(JSON.stringify(request.headers, true, 2));
        next();
      }
    }
    
    httpProxy.createServer(
      logger(), // <-- Here is all the magic
      {
        hostnameOnly: true,
        router: {
          'example1.com': '127.0.0.1:8001', // server on localhost:8001
          'example2.com': '127.0.0.1:8002'  // server 2 on localhost:8002
      }
    }).listen(8000);
    

    【讨论】:

    • 这还能用吗?当我访问不同的 url 但无法弄清楚时,我正在尝试记录请求...
    • 这不再起作用,因为现在必须在选项中传递某种目标或前向字段。运行上面的代码给了我必须为 Target 提供有效的 url。
    【解决方案3】:

    我喜欢在事件 proxyReq 上记录请求标头对象

    const http = require('http'),
        httpProxy = require('http-proxy'),
        fs = require('fs');
    
    const proxy = httpProxy.createProxyServer({});
    
    const logFile = fs.createWriteStream('./requests.log');
    
    proxy.on('proxyReq', function (proxyReq, req, res, options) {
        //Log incoming request headers
        logFile.write(JSON.stringify(req.headers, true, 2));
    });
    
    const server = http.createServer(function (req, res) {
        proxy.web(req, res, {
            changeOrigin: true,
            target: 'example1.com'
        });
    });
    
    console.log("listening on port 5050")
    server.listen(5050);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-21
      • 2014-03-01
      • 2016-02-19
      • 2014-12-01
      • 2017-10-11
      • 1970-01-01
      • 2018-10-22
      相关资源
      最近更新 更多