How to request HTTPS using http.request

Posted on
  • In the docs I can see there is provision for HTTPS when using http.get, you just pass a https:// url and it works it out. But what about when using http.request?

      var options = {
        host: 'google.com',
        port: 80,
        path: '/',
        method: 'GET',
      };
    
      console.log('about to http request');
      http.request(options, function(res) {
        console.log('request cb');
        res.on('data', function(data) {
          console.log("HTTP> "+data);
        });
    
        res.on('close', function(data) {
          console.log(data);
          console.log("Connection closed");
        });
    
        res.on('error', function(err) {
          console.log(err);
        });
      }).end();
    

    Works fine, but if I change the port to 443 it just stalls. I assume because its trying to talk HTTP to a HTTPS port. I don't really want to use tls.connect because that gives me a socket rather than a https connection.

  • Got it, you need to specify an undocumented parameter in options called protocol, and set it to https: (note the trailing colon).

    var options = {
        host: 'google.com',
        protocol: 'https:',
        port: 443,
        path: '/',
        method: 'GET',
      };
    
  • Thanks - I've just updated the docs, so it'll be on the main site next time I update

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

How to request HTTPS using http.request

Posted by Avatar for dave_irvine @dave_irvine

Actions