Skip to content

Instantly share code, notes, and snippets.

@jrc03c
Created January 7, 2023 16:43
Show Gist options
  • Save jrc03c/706b8edcb560ddd53d68a2ec44e526d9 to your computer and use it in GitHub Desktop.
Save jrc03c/706b8edcb560ddd53d68a2ec44e526d9 to your computer and use it in GitHub Desktop.
Basic HTTP / HTTPS server in Node w/ Express
const express = require("express")
const fs = require("fs")
const http = require("http")
const https = require("https")
// create a basic HTTP app that just redirects requests from HTTP to HTTPS
const httpApp = express()
httpApp.use((request, response) => {
return response.redirect("https://" + request.hostname + request.url)
})
// create the main app
const mainApp = express()
// mainApp.get(...)
// mainApp.post(...)
// mainApp.use(...)
// etc.
const sslConfig = {
key: fs.readFileSync("path/to/key.pem"),
cert: fs.readFileSync("path/to/cert.pem"),
}
// set the HTTP app to listen on port 80
http.createServer(httpApp).listen(80)
// set the HTTPS app to listen on port 443
https.createServer(sslConfig, mainApp).listen(443)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment