I needed a simple server to test my HTTPS POST requests. Just like a regular HTTP server, it is super easy to do in Node. Except I needed to add private key and a cert, which is an extra step and was not immediately obvious to me, so I figure I’d share my findings.
Step 1. Generate self signed Key and Cert
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout server.key -out server.crt
Code language: CSS (css)
Step 2. Create server file
Copy the code bellow into a server.js file (or whatever you want to call it, and run it with$ node server.js
"use strict";
var https = require('https');
var fs = require('fs');
var qs = require('querystring');
var options = {
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.crt')
};
var PORT = 8181;
function handleRequest(req, res){
//Process Post Request
if(req.method === "POST"){
var data = '';
req.on('data', function(chunk){
data += chunk;
});
req.on('end', function(){
var parseData = qs.parse(data);
var prettyData = JSON.stringify(parseData, null, 2);
console.log("Post request with:\n" + prettyData);
res.end(prettyData);
});
} else { //Send a simple response
res.end('Everything works');
}
}
//Create a server
var server = https.createServer(options, handleRequest);
//Start server
server.listen(PORT, function(){
console.log("Server listening on: https://localhost:" + PORT);
});
Code language: JavaScript (javascript)