我们有一个连接到服务器的客户端。服务器可以通过http 和https 两种方式访问。 https 服务器包含 CA 认证的 SSL key 。 由于客户端在公司代理后面运行,我们使用了以下命令:
const events = this.proxy ? new EventSource(this.source, { proxy: this.proxy }) : new EventSource(this.source)
因此,当前命令仅在连接到http://server时才有效。 .
如果我们尝试连接到 https://server ,收到以下错误:
Event { type: 'error', status: 400, message: 'Bad Request' }
所以我们尝试设置:
const events = this.proxy ? new EventSource(this.source, {https: {proxy: this.proxy, rejectUnauthorized: false} } ) : new EventSource(this.source)
或
const events = this.proxy ? new EventSource(this.source, {https: {proxy: this.proxy} } ) : new EventSource(this.source)
在这两种情况下,我们都收到超时错误。
我们有什么遗漏的吗?我们应该如何在代理后面设置https连接?
最佳答案
解决方案是使用“global-agent”或“global-tunnel-ng”包:
// Support working behind a corporate proxy
const MAJOR_NODEJS_VERSION = parseInt(process.version.slice(1).split('.')[0], 10);
if (MAJOR_NODEJS_VERSION >= 10) {
// `global-agent` works with Node.js v10 and above. Proxy env should be defined "export GLOBAL_AGENT_HTTP_PROXY=http://127.0.0.1:8080"
require('global-agent').bootstrap()
} else {
// `global-tunnel-ng` works only with Node.js v10 and below. Uses npm proxy settings
require('global-tunnel-ng').initialize()
}
const events = new EventSource(this.source)
阅读此处了解更多信息:https://www.npmjs.com/package/global-agent
关于node.js - 带有 https 代理的 NodeJS EventSource 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57507582/