Skip to content

Instantly share code, notes, and snippets.

@nadeesha
Last active July 28, 2017 06:15
Show Gist options
  • Save nadeesha/6863947 to your computer and use it in GitHub Desktop.
Save nadeesha/6863947 to your computer and use it in GitHub Desktop.
Node-based http/https proxy to forego the pain of configuring iptables for one-off dev tasks. Not recommended to be used in prod environments.
var fs = require('fs'),
http = require('http'),
https = require('https'),
httpProxy = require('http-proxy');
var isHttps = true; // do you want a https proxy?
var options = {
https: {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('key-cert.pem')
}
};
// this is the target server
var proxy = new httpProxy.HttpProxy({
target: {
host: '127.0.0.1',
port: 8080
}
});
if (isHttps)
https.createServer(options.https, function(req, res) {
console.log('Proxying https request at %s', new Date());
proxy.proxyRequest(req, res);
}).listen(443, function(err) {
if (err)
console.log('Error serving https proxy request: %s', req);
console.log('Created https proxy. Forwarding requests from %s to %s:%s', '443', proxy.target.host, proxy.target.port);
});
else
http.createServer(options.https, function(req, res) {
console.log('Proxying http request at %s', new Date());
console.log(req);
proxy.proxyRequest(req, res);
}).listen(80, function(err) {
if (err)
console.log('Error serving http proxy request: %s', req);
console.log('Created http proxy. Forwarding requests from %s to %s:%s', '80', proxy.target.host, proxy.target.port);
});
@zszszsz
Copy link

zszszsz commented Apr 4, 2016

well I have trouble with https

https.createServer({key:key,cert:cert}, (req,res)=>{
                console.log('request');
                res.writeHead(200, {'Content-Type': 'text/plain'});
                res.end('okay');
            }).on('connection'),(s)=>{console.log('connnection')
               .listen(l.port,l.host));

It turns out that when browser use the server as proxy to reach another host, the 'request' event seems not to be emmited, while the 'connection' event is emmited, leaving the CONNECTION request from the browser untouched.
it is on windows 10 and nodejs 5.

@zszszsz
Copy link

zszszsz commented Apr 4, 2016

well I'm sorry, it is actually a CONNECT request instead of CONNECTION

@aeroxy
Copy link

aeroxy commented Jul 28, 2017

httpProxy.HttpProxy is not a function used this package (wrong npm package?): https://www.npmjs.com/package/http-proxy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment