node.js - 带有 https 代理的 NodeJS EventSource 不起作用

标签 node.js https proxy

我们有一个连接到服务器的客户端。服务器可以通过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/

相关文章:

javascript - 让导出对象成为 CommonJS 中的函数可以吗?

java - SSL 不适用于 Android 2.2(仅适用于 2.3)

android - 我如何告诉 Android Volley 中的 TLS 版本

excel - 使用 WinHTTP 和 Excel 配置代理

python - Python 中的代码,在 Node.js 和 Socket.IO 中通信,在 HTML 中呈现

javascript - 如何在 NodeJS 中访问 SQL 请求的结果?

spring-boot - 带有企业代理的 Spring Cloud Feign/Ribbon

.net - 通过具有 Windows (NTLM) 身份验证的代理访问具有基本身份验证的 Web 服务

node.js - Nodejs every 和 foreach 循环

java - 开发可以处理 HTTPS 连接的代理 servlet