We saw in the last few articles how to create a HTTP server with Node JS. HTTP server was good enough for us to do so many operations that we've performed in the articles lately. In this specific article however, we will be looking at how to create HTTPS server instead.
We use HTTPS when we need secure sessions. A secure session implies that the web browser will encrypt everything you do with a digitally signed certificate. So obviously before you do HTTPS, you need to create certificates. Let's therefore spend some time to see how to create certificates for SSL.
Creating SSL Certificates
In order to generate a certificate, you need to download a small tool OpenSSL from https://code.google.com/p/openssl-for-windows/downloads/list
Download the version as per your system's specification, it's basically a Zip file. Once downloaded, extract the content to a specified location onto your hard drive.
Now open the location of the extracted content and copy the file openssl.cnf to the bin folder.
It is basically the configuration file for the openssl. Next, open CMD, change the directory to this folder and execute the following command.
openssl req -config openssl.cnf -x509 -days 365 -newkey rsa:1024 -keyout hostkey.pem -nodes -out hostcert.pem
The program will then ask you for a few peices of information for creating the certificate. In the end of everything, you will have two files hostcert.pem and hostkey.pem, which is our certificate and key file respectively, that we will be using in our HTTPS server.
Creating HTTPS server
Just like we do for HTTP, an import to node's HTTP module, for HTTPS we import the HTTPS module. Also, since we need to pass in the certificate and key file, we also need to import the filestream (fs) module to enable Node to read the files. The following is the code to create the HTTPS server.
- var https = require('https');
- var fs = require('fs');
-
- var options = {
- key: fs.readFileSync('hostkey.pem'),
- cert: fs.readFileSync('hostcert.pem')
- };
-
- https.createServer(options, function (req, res) {
- res.writeHead(200);
- res.end("hello world\n");
- }).listen(8000);
Of course you need to copy the files into the same location as the node program. Now if you look at the code above, you'll find that it is very similar to what we discussed before, like reading files, creating a HTTP server and so on. The change however is the https.createServer() method that takes one more parameter, which is the certificate and key for the SSL.
Now if you run the code and see it in a browser, this is how it looks:
Select proceed anyway option as of now, as our browser doesn't know about our awesome certificate.