Tuesday 12 September 2017

How to create an HTTPS server in Node.js?

How to create an HTTPS server in Node.js?

Question: Run Node with http?
var express = require('express');
var app = express();

//Include modules
var http = require('http').Server(app);
var io = require('socket.io')(http);


http.listen('8082', function() {
    console.log('http listening on *:8082');
});

You can run as http://localhost:8082


Question: What certificate you require for https?
  1. server.key
  2. server.crt
  3. Create a folder public/cert at root of your project and add above 2 files.



Question: Run Node with https?
var express = require('express');
var app = express();

//Include modules

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


var privateKey = fs.readFileSync('public/cert/server.key', 'utf8');
var certificate = fs.readFileSync('public/cert/server.crt', 'utf8');
var credentials = {key: privateKey, cert: certificate};
var httpsServer = https.createServer(credentials, app);
var io = require('socket.io')(httpsServer);

httpsServer.listen('8083', function() {
    console.log('https listening on *:8083');
});
 

You can run as https://localhost:8083