【问题标题】:Node.js - listener must be a function errorNode.js - 侦听器必须是函数错误
【发布时间】:2014-11-07 08:01:35
【问题描述】:

我正在尝试将 (How to create a simple http proxy in node.js?) 上接受的答案从 http 转换为 https。

当我尝试从浏览器访问代理时,服务器退出并抛出此错误:

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

这是我的代码:

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
  });
}

如您所见,我只做了很少的更改,我不知道如何解决这个问题。

有什么想法吗?

【问题讨论】:

    标签: javascript node.js ssl


    【解决方案1】:

    看起来您对 https.request 的参数有误 (http://nodejs.org/api/https.html#https_https_request_options_callback)。应该只是:

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

    您的证书信息应包含在链接页面中的选项对象中:

    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) {
      ...
    }
    

    【讨论】:

    • 当我尝试访问一个页面时,从代理 var 中删除 'ssl' 会抛出错误: throw er; // 未处理的 'error' 事件 -- 错误:34410095616:error:140770FC:SSLroutines:SSL23_GET_SERVER_HELLO:unknown protocol:../deps/openssl/openssl/ssl/s23_clnt.c:787
    【解决方案2】:

    我通过将函数名称作为参数而不是保存函数的变量传递来解决了这个错误

    【讨论】:

      猜你喜欢
      • 2013-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2018-11-24
      • 1970-01-01
      相关资源
      最近更新 更多