简体   繁体   English

如何使用 node.js http-proxy 在计算机中记录 HTTP 流量?

[英]How do I use node.js http-proxy for logging HTTP traffic in a computer?

I am trying to implement the simplest example:我正在尝试实现最简单的示例:

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);

When I configure my browser to use this proxy and I navigate to www.google.com I receive no response.当我将浏览器配置为使用此代理并导航到 www.google.com 时,我没有收到任何响应。 What is that I am doing wrong?我做错了什么?

I'm using Windows 7 Chrome我正在使用 Windows 7 Chrome

Here is an simple example how to log requests. 这是一个如何记录请求的简单示例。 I use a similar to log all my domains to one database. 我使用类似的方法将我的所有域记录到一个数据库。

I copied much from http://blog.nodejitsu.com/http-proxy-middlewares 我从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);

I am not sure if this helps because the posted information are really short. 我不确定这是否有帮助,因为发布的信息非常简短。 But I found a post that they updated the api ... 但我找到了一个帖子,他们更新了api ...

you might want to check out this post: 你可能想看看这篇文章:

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

I done like logging the request headers object on the event proxyReq我喜欢在事件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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM