Forward http proxy using node http proxy
Asked Answered
D

1

3

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?

Donelu answered 14/12, 2017 at 21:2 Comment(0)
B
9

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...");
});
Brigidbrigida answered 15/12, 2017 at 19:17 Comment(4)
@AyushGoel correct. You're not going to be able to proxy HTTPS this easily (especially if you also want to modify the responses), if that's your intention.Brigidbrigida
Why is that? I should be able to do that using self signed certificates, and ask chrome to avoid certificate warnings (using --ignore-certificate-errors) Can you just give me the code for the bare bones forwarding proxy for https as well.Donelu
I've never used node-http-proxy to dynamically proxy HTTPS requests, so I can't give you any code.Brigidbrigida
@AyushGoel there are examples on how to forward http(s)->http(s) github.com/http-party/node-http-proxy/tree/master/examples/httpRamshackle

© 2022 - 2024 — McMap. All rights reserved.