NodeJS HTTPS

Home / NodeJS HTTPS

NodeJS HTTPS

December 11, 2015 | Article | No Comments

HTTPS or HTTP Secure is the HTTP protocol over TLS. It is the secure version of HTTP and implemented as separate module in Node. The API itself is very similar to the HTTP one, with some small differences.

HTTPS Server

To create a server, we can do:

var https = require('https'),
    fs = require('fs');

var options = {
    key: fs.readFileSync('/path/to/server/private-key.pem');
    cert: fs.readFileSync('/path/to/server/certificate.pem');
};

https.createServer(options, function(req,res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World!');
});

So here, the first argument to https.createServer is an options object that much like in TLS module, provides the private key and the certificate strings.

HTTPS Client

To make a HTTPS request, we must use https module:

var https = require('https'),
    options = {
        host: 'encrypted.google.com',
        port: 443,
        path: '/',
        method: 'GET'
    };

var req = https.request(options, function(res) {
    console.log("statusCode: ", res.statusCode);
    console.log("headers: ", res.headers);

    res.on('data', function(d) {
        process.stdout.write(d);
    });
});
req.end();

Here options we can change:

  • port: port of host to request to. Defaults is 443
  • key: the client private key string to use for SSL. Defaults to null.
  • cert: the client certificate to use. Defaults to null
  • ca: an authority certificate or array of authority certificates to check the remote host against.

We may want to use the key and cert options if the server needs to verify the client.

Much like http module, this module also offers a shortcut https.get method that can be used:

var https = require('https');
var options = { host: 'encrypted.google.com', path: '/' };
https.get(options, function(res) {
    res.on('data', function(d) {
        process.console.log(d.toString());
    });
});

, ,

About Author

about author

xathrya

A man who is obsessed to low level technology.

Leave a Reply

Your email address will not be published. Required fields are marked *

Social media & sharing icons powered by UltimatelySocial