E
E
Eugene2019-07-21 21:10:37
Node.js
Eugene, 2019-07-21 21:10:37

How to proxy https requests in node.js?

How to use a proxy for https requests? Everyone advises using the request npm package, but how do you do it using standard nodejs modules?
The following code results in an error:

const http = require("https");

const options = {
  host: "my-proxy",
  port: "my-proxy-port",
  path: "https://www.google.com",
};
http.get(options, function(res) {
  console.log(res);
  res.pipe(process.stdout);
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2019-07-25
@you_are_enot

The solution turned out to be ridiculously simple.
https://github.com/nodejs/node-v0.x-archive/issues/2474

var http = require('http');
var https = require('https');

var connectReq = http.request({ // establishing a tunnel
  host: 'localhost',
  port: 3128,
  method: 'CONNECT',
  path: 'github.com:443',
}).on('connect', function(res, socket, head) {
  // should check res.statusCode here
  var req = https.get({
    host: 'github.com',
    socket: socket, // using a tunnel
    agent: false    // cannot use a default agent
  }, function(res) {
    res.setEncoding('utf8');
    res.on('data', console.log);
  });
}).end();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question