4
#!/usr/bin/env node
let debug = require('debug')('sbl');
let app = require('../app');
let config = require('config');

app.set('port', process.env.NODE_PORT || config.sbl.port || 15000);

let server = app.listen(app.get('port'), function() {
  debug('Express server listening on port ' + server.address().port);
  console.logger.debug('Express server listening on port ' + server.address().port);
});

This is what it looks like so far and works fine with http.

How do I make it work with https?

systemdebt
  • 4,589
  • 10
  • 55
  • 116
  • 1
    This is still a relevant question as it can lead new users to a correct way to do things with grabbing keys and certs as demonstrated by the chosen answer. The redirect is appropriate, but moderators need to think twice before saying the exact question has been answered. Maybe in your mind, but this is a good question imo Simran! – DORRITO Jan 28 '20 at 20:33

1 Answers1

7

You can use the createServer function available in both 'http' and 'https' modules.

const express = require('express');
const http = require('http');
const https = require('https');
const fs = require('fs');

const app = express();

// start http server
const port = process.env.NODE_PORT || config.sbl.port || 15000;
let server = http.createServer(app).listen(port);

// start https server
let sslOptions = {
   key: fs.readFileSync('key.pem'),
   cert: fs.readFileSync('cert.pem')
};

let serverHttps = https.createServer(sslOptions, app).listen(443)

You can generate your certificates with openssl.

Guido
  • 46,642
  • 28
  • 120
  • 174
  • Thanks. But what about let server = app.listen(app.get('port'), function() { debug('Express server listening on port ' + server.address().port); console.logger.debug('Express server listening on port ' + server.address().port); }); Do I keep this or remove this? – systemdebt Feb 03 '18 at 18:14
  • I am not using http.createServer anywhere in my application as of now – systemdebt Feb 03 '18 at 18:17
  • 2
    You can remove the app.listen(xxx). According to the docs (http://expressjs.com/en/api.html#app.listen) this call is identical to Node’s http.Server.listen(). You can also see in the docs an example to create an http+https server. The code is the same I've posted in the answer, using createServer. Maybe it's clearer if you call it const app = express(); – Guido Feb 03 '18 at 18:20
  • Thx @jfriend00, it's fixed now. – Guido Feb 03 '18 at 19:44