JamesNW
JamesNW

Reputation: 125

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. I use both https and request+global-tunnel and neither solutions seem to work.
The similar code with 'http' works. 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.

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

Upvotes: 10

Views: 30118

Answers (1)

Kevin M
Kevin M

Reputation: 1574

You probably want to establish a TLS encrypted connection between your node app and target destination through a proxy.

In order to do this you need to send a CONNECT request with the target destination host name and port. The proxy will create a TCP connection to the target host and then simply forwards packs between you and the target destination.

I highly recommend using the request client. This package simplifies the process and handling of making HTTP/S requests.

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

Upvotes: 24

Related Questions