0

I using https.createServer to create a secure connection server, however, it won't work on my custom port http://localhost:2019.

Following is my code:

const options = {
    key:fs.readFileSync('security/privkey1.pem'),
    cert:fs.readFileSync('security/cert1.pem')
}
const app = express()
const https = require('https').createServer(options, app).listen(2019)

app.use(function(req, res, next) {
    console.log("checking secure connection")
    if(req.secure){
        next();
    }else{
        res.redirect('https://' + req.headers.host + req.url);
    }
});

When I access to https://localhost:2019, it work perfectly but when I access to http://localhost:2019, it won't reach the server (the console didn't print "checking secure connection").

Nodejs expert please advise please advise.

Thank you.

Jerry
  • 1,455
  • 1
  • 18
  • 39
  • You can't access the page via HTTP because you have started the HTTPS server, so the server listens for HTTPS connections. If you want to be able to access the page both via http:// and https://, then you need to start two servers, one using `http` module, and the other using `https`. If you want to follow convention, then you can start the `http` server and just redirect connections to the https one – Sebastian Kaczmarek Oct 07 '19 at 08:03
  • @SebastianKaczmarek I can't have both http server and https server to listen same port at the same time, the application crashed. – Jerry Oct 07 '19 at 08:30
  • 1
    So you *have to* listen on the same port, right? This might be helpful then: https://stackoverflow.com/questions/22453782/nodejs-http-and-https-over-same-port – Sebastian Kaczmarek Oct 07 '19 at 13:08

1 Answers1

0

You are creating a server on https, port 2019. That means you can access your server via https on port 2019. You can create a http server on another port and redirect traffic from there to https on 2019.

baao
  • 71,625
  • 17
  • 143
  • 203