简体   繁体   English

如何将https代理与node.js https / request Client一起使用?

[英]How can I use an https proxy with node.js https/request Client?

I need to send my client HTTPS requests through an intranet proxy to a server. 我需要通过Intranet代理将客户端HTTPS请求发送到服务器。 I use both https and request+global-tunnel and neither solutions seem to work. 我同时使用https和request + global-tunnel,但两种解决方案似乎都不起作用。
The similar code with 'http' works. 与“ http”相似的代码可以工作。 Is there other settings I missed? 我还有其他设置吗?

The code failed with an error: 代码失败并出现错误:

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)

The code is the simple https test. 该代码是简单的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);
});

You probably want to establish a TLS encrypted connection between your node app and target destination through a proxy. 您可能想通过代理在节点应用程序和目标目标之间建立TLS加密连接。

In order to do this you need to send a CONNECT request with the target destination host name and port. 为此,您需要发送带有目标目的地主机名和端口的CONNECT请求。 The proxy will create a TCP connection to the target host and then simply forwards packs between you and the target destination. 代理将创建到目标主机的TCP连接,然后简单地在您和目标目的地之间转发数据包。

I highly recommend using the request client . 我强烈建议使用请求客户端 This package simplifies the process and handling of making HTTP/S requests. 该程序包简化了发出HTTP / S请求的过程和处理。

Example code using 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);
    }
});

Example code using no external dependencies: 不使用外部依赖项的示例代码:

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM