Skip to content

Instantly share code, notes, and snippets.

@daniel12fsp
Last active October 29, 2018 20:57
Show Gist options
  • Save daniel12fsp/57684a9ad2b2bb66f8e0e9fe312090cb to your computer and use it in GitHub Desktop.
Save daniel12fsp/57684a9ad2b2bb66f8e0e9fe312090cb to your computer and use it in GitHub Desktop.
Simple HTTPS Server in Node
const tls = require('tls');
const fs = require('fs');
/*
To generate a valid certificate in command line:
openssl req -x509 -newkey rsa:2048 -keyout keytmp.pem -out cert.pem -days 365
openssl rsa -in keytmp.pem -out key.pem
*/
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem'),
rejectUnauthorized: true,
};
const server = tls.createServer(options, (socket) => {
console.log('server connected',
socket.authorized ? 'authorized' : 'unauthorized');
socket.on("error", function (err) {
console.log(err)
})
socket.on('data', function (data) {
const header = data.toString();
console.log("--------start request--------");
console.log(header);
console.log("--------end request--------");
let response = "HTTP/1.1 200 OK\r\n";
body = "<h1> HELLO WORLD &#128521; in HTTPS </h1>";
response += 'Content-Length: ' + body.length + '\r\n';
response += 'Content-Type: text/html; charset=utf-8\r\n';
response += '\r\n';
response += body;
socket.write(response);
socket.setEncoding('utf8');
socket.pipe(socket);
})
});
server.listen(8080, 'localhost');
@johnatandias
Copy link

Simple and useful...

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