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?

1 Answer 1

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...");
});
Sign up to request clarification or add additional context in comments.

4 Comments

@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.
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.
I've never used node-http-proxy to dynamically proxy HTTPS requests, so I can't give you any code.
@AyushGoel there are examples on how to forward http(s)->http(s) github.com/http-party/node-http-proxy/tree/master/examples/http

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.