Created
January 7, 2023 16:43
-
-
Save jrc03c/706b8edcb560ddd53d68a2ec44e526d9 to your computer and use it in GitHub Desktop.
Basic HTTP / HTTPS server in Node w/ Express
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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