I have a node server that looks like this:
const express = require("express");
const app = express();
const port = 8000;
const https = require("https");
const fs = require("fs");
const credentials = {
key: fs.readFileSync("../auth/key.pem"),
cert: fs.readFileSync("../auth/cert.pem"),
};
const server = https.createServer(credentials, app);
const io = require("socket.io")(server, { cors: { origin: "*" } });
app.get("/", (req, res) => {
console.log("redirecting http to https");
if (req.headers.host.match(/^www/) !== null || !req.secure) {
return res.redirect(
"https://" + req.headers.host.replace(/^www\./, "") + req.url
);
}
});
server.listen(port, () => console.log(`Server is running on port ${port}`));
It should redirect any query from http to https. However, if I go to http://.com/ I get:
<myurl>.com didn’t send any data.
ERR_EMPTY_RESPONSE
I assume this is because in my server, I used https, not http. I can't use http, as I need the server to have an ssl certificate, which requires https. Whatever I end up with, it can only run on one port, so is there any way to implement logic that if a request hits http://.com/ it redirects to https?