node.js - 如何将 https 代理与 node.js https/request 客户端一起使用?

标签 node.js https proxy

我需要通过 Intranet 代理将我的客户端 HTTPS 请求发送到服务器。 我同时使用 https 和 request+global-tunnel,这两种解决方案似乎都不起作用。
与“http”类似的代码有效。我还遗漏了其他设置吗?

代码因错误而失败:

REQUEST:
problem with request: tunneling socket could not be established, cause=socket hang up

HTTPS:
events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: socket hang up
    at SecurePair.error (tls.js:1011:23)
    at EncryptedStream.CryptoStream._done (tls.js:703:22)
    at CleartextStream.read [as _read] (tls.js:499:24)

代码是简单的https测试。

var http = require("https");

var options = {
  host: "proxy.myplace.com",
  port: 912,
  path: "https://www.google.com",
  headers: {
    Host: "www.google.com"
  }
};

http.get(options, function(res) {
  console.log(res);
  res.pipe(process.stdout);
});

最佳答案

您可能希望通过代理在您的 Node 应用程序和目标目的地之间建立 TLS 加密连接。

为此,您需要发送带有目标主机名和端口的 CONNECT 请求。代理将创建到目标主机的 TCP 连接,然后简单地在您和目标目的地之间转发数据包。

我强烈推荐使用 request client .这个包简化了发出 HTTP/S 请求的过程和处理。

示例代码使用 request client :

var request = require('request');

request({
    url: 'https://www.google.com',
    proxy: 'http://97.77.104.22:3128'
}, function (error, response, body) {
    if (error) {
        console.log(error);
    } else {
        console.log(response);
    }
});

不使用外部依赖的示例代码:

var http = require('http'),
    tls = require('tls');

var req = http.request({
    host: '97.77.104.22',
    port: 3128,
    method: 'CONNECT',
    path: 'twitter.com:443'
});

req.on('connect', function (res, socket, head) {
    var tlsConnection = tls.connect({
        host: 'twitter.com',
        socket: socket
    }, function () {
        tlsConnection.write('GET / HTTP/1.1\r\nHost: twitter.com\r\n\r\n');
    });

    tlsConnection.on('data', function (data) {
        console.log(data.toString());
    });
});

req.end();

关于node.js - 如何将 https 代理与 node.js https/request 客户端一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34078995/

相关文章:

node.js - 在本地测试 Instagram Basic API

.net - SSL 和 ASP.NET MVC

web-services - 通过命令提示符创建代理(SSL 证书)

javascript - 如何使用 vanilla Node.js 运行 500 个请求,其中 20 个并行

javascript - 如何将 Node.js 流的内容读入字符串变量?

node.js - Node.js 如何处理非阻塞 IO,即使它是单线程的?

html - 如何在 IE9 中使用协议(protocol)相关 URL?

ssl - 从 curl 客户端解耦 SSL 负载

javascript - 407 需要代理身份验证(Forefront TMG 需要授权才能完成请求。对 Web 代理过滤器的访问被拒绝。)

javascript - 我怎样才能故意让我的 node.js 服务器崩溃?