Marco Gabriel Godoy Lema Marco Gabriel Godoy Lema - 3 months ago 30
Node.js Question

Node.js+express proxy ssl

I'm trying to write a reverse proxy in node.js using express, and it works fine for http requests. The problem is that when requesting https it never responds, and the browser states that the proxy refused to connect.
Here is the working code for http requests:

var app = express(),
http=require('http');

app.configure(function(){ /* express stuff to log and use routes and the like */ });

http.createServer(app).listen(8000, function(){
console.log("Express server listening on port " + 8000);
});

app.all('*', proxy);
var request=require('request');

var proxy=function(req,resp){
var data={
url:req.url,
headers: {
'Connection': 'keep-alive'
}
}
var proxy=request(req.url);
proxy.pipe(resp);
}


Now, as for SSL, i am currently trying with:

var https=require('https'),
fs=require('fs');

https.createServer({
key: fs.readFileSync(__dirname+'/ssl/server.key', 'utf8'),
cert: fs.readFileSync(__dirname+'/ssl/server.crt', 'utf8')
},app).listen(8001, function(){
console.log("Express server listening on port " + 8001);
});


The proxy can be used from anywhere requiring
50.56.195.215:8000
for HTTP and
50.56.195.215:8001
for SSL. It has no security whasoever, so don't log in to anything important =D

I'm using a self signed SSL Certificate, and i guess it's kind of silly of me to try to do such a thing, but i don't have any ideas left :P

Answer

My suggestion is use the great existing library node-http-proxy from Nodejitsu. If you want to write your own, at least study their source code academically.

Some notes on your approach above:

  • You aren't handling HTTP methods other than GET (POST, PUT, DELETE, etc). These exist. You must handle them if you want your proxy to actually work. Every time you call request(req.url), request is making a GET request by default.