Forward http proxy using node http proxy

落爺英雄遲暮 提交于 2019-12-24 20:53:39

问题


I'm using the node-http-proxy library to create a forward proxy server. I eventually plan to use some middleware to modify the html code on the fly. This is how my proxy server code looks like

var  httpProxy = require('http-proxy')
httpProxy.createServer(function(req, res, proxy) {
  var urlObj = url.parse(req.url);
  console.log("actually proxying requests")
  req.headers.host  = urlObj.host;
  req.url           = urlObj.path;

  proxy.proxyRequest(req, res, {
    host    : urlObj.host,
    port    : 80,
    enable  : { xforward: true }
  });
}).listen(9000, function () {
  console.log("Waiting for requests...");
});

Now I modify chrome's proxy setting, and enable web proxy server address as localhost:9000

However every time I visit a normal http website, my server crashes saying "Error: Must provide a proper URL as target"

I am new at nodejs, and I don't entirely understand what I'm doing wrong here?


回答1:


To use a dynamic target, you should create a regular HTTP server that uses a proxy instance for which you can set the target dynamically (based on the incoming request).

A bare bones forwarding proxy:

const http      = require('http');
const httpProxy = require('http-proxy');
const proxy     = httpProxy.createProxyServer({});

http.createServer(function(req, res) {
  proxy.web(req, res, { target: req.url });
}).listen(9000, () => {
  console.log("Waiting for requests...");
});


来源:https://stackoverflow.com/questions/47821987/forward-http-proxy-using-node-http-proxy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!