Friday, March 5, 2021

Node.JS : Enable HTTPS on Express JS


How to enable HTTPS on Express Node.JS?

Step 1 : $ npm install express
Step 2 : Download & Install OpenSSL
Step 3 : Generate file *.crt and *.key using OpenSSL
             $ openssl req -x509 -sha256 -nodes -newkey rsa:2048 -days 365 -keyout localhost.key -out localhost.crt -config "C:\OpenSSL-Win64\share\openssl.cnf"
Step 4 : Write Code 
Step 5 : Done

You can follow the syntax below to enable HTTPS on Express Node.JS 

/*
	NodeJS HTTPS Server Example
	--------------------------------------------------

	Step 1 : $ npm install express
	Step 2 : Download & Install OpenSSL
		 - http://gnuwin32.sourceforge.net/packages/openssl.htm
	Step 3 : Generate file *.crt and *.key using OpenSSL
		 $ openssl req -x509 -sha256 -nodes -newkey rsa:2048 -days 365 -keyout localhost.key -out localhost.crt -config "C:\OpenSSL-Win64\share\openssl.cnf"
	Step 5 : Write Code 
	Step 6 : Run
		 $ node static-file-webserver.js
	Step 7 : Done

	--------------------------------------------------
	Reference :
		- https://stackoverflow.com/a/11745114/9278668
		- https://stackoverflow.com/a/32169444/9278668
		- https://stackoverflow.com/a/19400134/9278668
*/

var fs = require('fs');
var http = require('http');
var https = require('https');
var privateKey  = fs.readFileSync('localhost.key', 'utf8');
var certificate = fs.readFileSync('localhost.crt', 'utf8');

var credentials = {key: privateKey, cert: certificate};

var path = require('path');
var express = require('express');
var app = express();

var dir = path.join(__dirname, '');

app.use(express.static(dir));

var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);

httpServer.listen(80, function() {
	console.log('HTTP Server Running...');
});
httpsServer.listen(443, function() {
	console.log('HTTPS Server Running...');
});


Reference :
Previous Post
Next Post

0 komentar: