Javascript Node.js - 监听器必须是函数错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25820174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js - listener must be a function error
提问by Brian Smith
I'm trying to convert the accepted answer on (How to create a simple http proxy in node.js?) from http to https.
我正在尝试将接受的答案(如何在 node.js 中创建一个简单的 http 代理?)从 http 转换为 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?
有任何想法吗?
采纳答案by Rob M.
Looks like you've got the arguments to https.requestwrong (http://nodejs.org/api/https.html#https_https_request_options_callback). Should just be:
看起来你的论点是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
});
});
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) {
...
}
回答by Janac Meena
I solved this error by passing the function name as the param rather than the variable that holds the function
我通过将函数名称作为参数而不是保存函数的变量传递来解决了这个错误

