Skip to content

Instantly share code, notes, and snippets.

@leommoore
Last active January 17, 2021 18:19
Show Gist options
  • Save leommoore/5066015 to your computer and use it in GitHub Desktop.
Save leommoore/5066015 to your computer and use it in GitHub Desktop.
Node - Https Server

#Node.js https & Express (SSL) Server

A simple https server using node.js (v0.10.0):

var https = require("https");
var  fs = require("fs");
 
var options = {
  key: fs.readFileSync('privatekey.pem'),
  cert: fs.readFileSync('certificate.pem')
};

https.createServer(options, function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8000);

console.log("Server running at https://127.0.0.1:8000/")

A simple https Express server using node.js (v0.10.0):

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

var app = express();

app.get('/', function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World Express\n');
});

var options = {
  key: fs.readFileSync('certs/privatekey.pem'),
  cert: fs.readFileSync('certs/certificate.pem')
};

var server = https.createServer(options, app);
server.listen(443, function() {
});

console.log("Server running at https://localhost:443/");

You can generate the privatekey.pem and certificate.pem files using the following commands:

openssl genrsa -out privatekey.pem 1024 
openssl req -new -key privatekey.pem -out certrequest.csr 
openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem
@ki9us
Copy link

ki9us commented Jan 17, 2021

I think you meant:

var server = https.createServer(options, app);
server.listen(443, function() {
  console.log("Server running at https://localhost:443/");
});

instead of

var server = https.createServer(options, app);
server.listen(443, function() {
});

console.log("Server running at https://localhost:443/");

at the end of the express example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment