Skip to content

Instantly share code, notes, and snippets.

@jyek
Forked from leommoore/node_https_server.md
Created May 30, 2014 23:24
Show Gist options
  • Save jyek/5d187e535d2e8619e7fd to your computer and use it in GitHub Desktop.
Save jyek/5d187e535d2e8619e7fd to your computer and use it in GitHub Desktop.

#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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment