Open In App

HTTPS in Node.js

HTTP: When the data is transferred in HTTP protocol it just travels in the clear text format. 

HTTPS: It simply encrypts the request from the browser to the web server, so it is tough to sniff that information. It basically works on two things: 



Both of these use a PKI (Public Key Infrastructure) 

There are various advantages to this additional layer: 



An Example of setting up an HTTPS server with Node.Js is as follows: 

Example 1: In this example, we will set up an HTTPS server with NodeJs.




(function() {
 
// Reading and writing to files in Node.js
// working with directories or file system
const fs = require("fs");
 
    // Responsible for creating HTTPS server
    // taking options for the server
    // options like where your certificates
    // and private key files are located
    // also take actual request and response server
    // code for parsing web pages from files
    const https = require("https");
 
    // Helps with mimetypes in creating our response header
    const path = require("path");
 
    // "text/css" is added in response header
    // so browser knows how to handle it
    let mimetypes = {
        "css":"text/css",
    "html":"text/html"
};
 
    // Options is used by the servers
    // pfx handles the certificate file
    let options = {
        pfx: fs.readFileSync("ssl/cert.pfx"),
    passphrase: "encrypted"
};
 
    let server = https.createServer(options, function(request, response) {
  
    // If the url is empty
    if (request.url == "" || request.url == "/") {
        request.url = "homepage.html";
    }
 
    // __dirname is the directory where we are getting
    // these files from __dirname holds the file route
    // request.url is the index.html we made earlier
    // function is the callback function that holds two
    // parameters
    fs.readFile(__dirname + "/" + request.url, function(err, content) {
        if (err) {
        console.log("Error: " + err);
        }
    else {
 
        // 200 is code for OK
        // content-Type is the object or the content header
        response.writeHead(200,
            { 'Content-Type': mimetypes[path.extname(request.url).split(".")[1]] });
    response.write(content);
        }
 
    // This will send our response back to the browser
    response.end();
    });
});
 
    server.listen("port number", "IP Address", function() {
 
        console.log("Server has started!");
});
  
})();

Output: Whatever the port number and IP Address are given to the server.listen it will execute that only web page whenever requested. And this web page will be HTTPS.


Article Tags :