We have seen in the last few posts how we can create Http server with Node JS. Http server was good enough for us to do so many operations that we’ve performed in the posts lately. In this particular post however, we will be looking at how we can create HTTPS server instead.
We use HTTPS when we need secure sessions. Secure sessions 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 we can 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 in a specified location onto your hard drive.
Now open the location of the extracted content ans copy the file openssl.cnf inside the bin folder.
It is basically the configuration file for the openssl. Next, open CMD, change 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 would then ask you for few information in order to create a certificate. In the end of everything, you will have two files hostcert.pem and hostkey.pem, which is our certificate and key file respectively, which 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 HTTPS module. Also since we need to pass in the certificate and Key file, we also require to import filestream (fs) module in order to enable Node to read the files. Following is the code to create the HTTPS server.
1: var https = require('https');
2: var fs = require('fs');
3:
4: var options = {
5: key: fs.readFileSync('hostkey.pem'),
6: cert: fs.readFileSync('hostcert.pem')
7: };
8:
9: https.createServer(options, function (req, res) {
10: res.writeHead(200);
11: res.end("hello world\n");
12: }).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 pretty much similar stuff that we have discussed before, like reading files, creating http server etc. The change however is the https.createServer() method takes one more parameter, which are the certificate and key for the SSL.
Now if you run the code and see it via browser, this is how it looks like:
Select proceed anyway option as of now, as our browser don’t know about our awesome certificate.
This is all how you create a https server in node js.
Happy Coding!!!
0 comments