Search code examples
node.jsnodejs-server

nodejs express force to stay on http


Working on a NodeJs application and I'd like to trick the browser so that to keep http, latest version of the browser keep redirecting this to https.

I know that its not recommended but its only for PoC so no major issue having unsecured communication.

var port = 80;

server.listen(port, function () {
    console.log('webapp: listening at port %d', port);
});

    // Routing
    const currentDirectory = path.join(__dirname, '../', 'webapp');
    app
        .get('/', applyTemplate('index.html'))
        .get('/index.html', applyTemplate('index.html'))
        .use(express.static(currentDirectory))

Can I trick the browser? To handle the https connection and redirect it to http without creating a ssl certificate.


Solution

  • You need to create a self-signed certificate with openssl and then use it. If not, modern browsers will try to protect you by blocking some operations. Those checks are very important and you should be aware they exist in order to write a correct and working code. You can easily send passwords or sensitive data between HTTPS and HTTP if you start changing browsers behavior. May I ask you the reason you want to skip those checks? Most of the times a well done test suite is more than enough to handle those cases in a proper way having the correct response from the browser.

    I am attaching an example you can find at => https://timonweb.com/posts/running-expressjs-server-over-https/

    openssl req -nodes -new -x509 -keyout server.key -out server.cert
    
    var express = require('express')
    var fs = require('fs')
    var https = require('https')
    var app = express()
    
    app.get('/', function (req, res) {
      res.send('hello world')
    })
    
    https.createServer({
      key: fs.readFileSync('server.key'),
      cert: fs.readFileSync('server.cert')
    }, app)
    .listen(3000, function () {
      console.log('Example app listening on port 3000! Go to https://localhost:3000/')
    })