gpt4 book ai didi

javascript - Node.js - listener must be a function 错误

转载 作者:搜寻专家 更新时间:2023-10-31 23:09:24 25 4
gpt4 key购买 nike

我正在尝试将 ( 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
});
}

如您所见,我只做了很少的改动,我不确定如何解决这个问题。

有什么想法吗?

最佳答案

看起来您的 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) {
...
}

关于javascript - Node.js - listener must be a function 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25820174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com