5

I'm trying to convert the accepted answer on (How to create a simple http proxy in node.js?) from http to https.

When I try to access the proxy from my browser, the server quits and throws this error :

events.js:171
    throw TypeError('listener must be a function');
      ^
TypeError: listener must be a function

Here is my code :

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

var ssl = {
    ca: fs.readFileSync("cacert.pem"),
    key: fs.readFileSync("key.pem"),
    cert: fs.readFileSync("cert.pem")
};

https.createServer(ssl, onRequest).listen(3000, '127.0.0.1');

function onRequest(client_req, client_res) {

  console.log('serve: ' + client_req.url);

  var options = {
    hostname: 'www.example.com',
    port: 80,
    path: client_req.url,
    method: 'GET'
  };

  var ssl = {
    ca: fs.readFileSync("cacert.pem"),
    key: fs.readFileSync("key.pem"),
    cert: fs.readFileSync("cert.pem")
  };

  var proxy = https.request(ssl, options, function(res) {
    res.pipe(client_res, {
      end: true
    });
  });

  client_req.pipe(proxy, {
    end: true
  });
}

As you can see, I made very little changes and I'm not sure how to fix this.

Any ideas?

Community
  • 1
  • 1
Brian Smith
  • 1,443
  • 5
  • 18
  • 24

2 Answers2

4

Looks like you've got the arguments to https.request wrong (http://nodejs.org/api/https.html#https_https_request_options_callback). Should just be:

var proxy = https.request(options, function(res) {
   res.pipe(client_res, {
     end: true
   });
 });

Your certificate information should be included in the options object, from the linked page:

var options = {
  hostname: 'encrypted.google.com',
  port: 443,
  path: '/',
  method: 'GET',
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};
options.agent = new https.Agent(options);

var req = https.request(options, function(res) {
  ...
}
Rob M.
  • 35,491
  • 6
  • 51
  • 50
  • removing the 'ssl' from the proxy var throws and error when I try to access a page : throw er; // Unhandled 'error' event -- Error: 34410095616:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:../deps/openssl/openssl/ssl/s23_clnt.c:787 – Brian Smith Sep 13 '14 at 06:08
1

I solved this error by passing the function name as the param rather than the variable that holds the function

Janac Meena
  • 3,203
  • 35
  • 32