I have an server running express. It uses req.protocol to force https. However, when I visit the site on http, it still give https.
Here is the function:
app.use((req, res, next)=>{
console.log(req.protocol);
if(req.protocol === "https"){
next();
}else{
res.redirect(`https://${req.headers.host}${req.url}`);
}
});
It isn't redirecting and therefore the site isn't working. What can I do to fix this?
CodePudding user response:
It sounds like your server is only responding to HTTPS requests, not HTTP requests. Remember you serve HTTP and HTTPS on separate ports (80 and 443, by default). From your description, it sounds like you're only serving HTTPS. Here's the example from the Express listen docs for how they serve both:
var express = require('express')
var https = require('https')
var http = require('http')
var app = express()
http.createServer(app).listen(80)
https.createServer(options, app).listen(443)
Note that they called listen twice, once each on two different servers, one for HTTP and another for HTTPS.
