cVos
cVos

Reputation: 27

Can't figure out SSL with node and express (https)

I've been working at making a website, but after getting my website to work I set out to try and get SSL so the annoying "warning" symbol would go away. Unfortunately I've come to a real impasse and all the resources I've found to help me work through this seem to be outdated or at least not compatible with what I'm doing.

My original working server.js file:

const express = require('express');
const path = require('path');
const app = express();
const port = process.env.PORT || 3000;

app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, '/index.html'));
});

app.listen(port);

What I tried but ends up not working:

const fs = require('fs');

const options = {
  cert: fs.readFileSync('cert/certificate.crt'),
  ca: fs.readFileSync('cert/ca_bundle.crt'),
  key: fs.readFileSync('cert/private.key')
};

const express = require('express');
const path = require('path');
const app = express();
const port = process.env.PORT || 3000;
const httpsPort = process.env.PORT || 3030;

app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, '/index.html'));
});

app.listen(port);
httpsPort.createServer(options, app).listen(httpsPort);

I am struggling to wrap my head around the entire venture since I've started on this https issue. Help would be greatly appreciated!

Upvotes: 0

Views: 100

Answers (1)

Andrey Popov
Andrey Popov

Reputation: 7510

Uhm, there are a few issues here. First you try to listen on two different things. app.listen is a short version of http.createServer({ ...options }, app).

Second - your code is httpsPort.createServer(options, app).listen(httpsPort);, which basically translates to 3030.createServer(options, app).listen(3030). Here's what I usually do:

const https = require('https');
const server = https.createServer(options, app).listen(port)

If you would like to support both, then you need to include both http and https packages, and have an if-else (or something similar) so that you use the proper package to create the server.

You should not listen on the app in this scenario!

Upvotes: 1

Related Questions