HTTPS: Make the Application Speak HTTPS
We'll cover the following...
Objective
- Migrate our endpoint from HTTP to HTTPS.
Steps
- Make the application speak HTTPS.
- Remove the HTTP endpoint.
Making our application speak HTTPS
Let’s update our application to listen to HTTPS requests on port 8443. We’re going to make the application use the self-signed certificate that the EC2 instance generated in the UserData
script when it came online.
Press + to interact
const { hostname } = require('os');const http = require('http');const https = require('https');const fs = require('fs');const STACK_NAME = process.env.STACK_NAME || "Unknown Stack";const port = 8080;const httpsPort = 8443;const httpsKey = '../keys/key.pem'const httpsCert = '../keys/cert.pem'if (fs.existsSync(httpsKey) && fs.existsSync(httpsCert)) {console.log('Starting https server')const message = `Hello HTTPS World from ${hostname()} in ${STACK_NAME}\n`;const options = { key: fs.readFileSync(httpsKey), cert: fs.readFileSync(httpsCert) };const server = https.createServer(options, (req, res) => {res.statusCode = 200;res.setHeader('Content-Type', 'text/plain');res.end(message);});server.listen(httpsPort, hostname, () => {console.log(`Server running at http://${hostname()}:${httpsPort}/`);});}console.log('Starting http server')const message = `Hello HTTP World from ${hostname()} in ${STACK_NAME}\n`;const server = http.createServer((req, res) => {res.statusCode = 200;res.setHeader('Content-Type', 'text/plain');res.end(message);});server.listen(port, hostname, () => {console.log(`Server running at http://${hostname()}:${port}/`);});
Line #3: Import the https
node library.
Line #8: We’ll use 8443 as our local HTTPS port number. ...