0

I would like to implement Node.js with Express for static content over HTTPS. Scouring the Web reveals tons of examples of Express with HTTPS and tons of examples of Express serving a static directory, but I cannot find an example using all three Express, HTTPS and static.

Moreover, looking at the examples I can find, I cannot piece together how to accomplish this.

Here is what I have found:

Express Static Directory over HTTP

var fs = require('fs')
var app = require("express");

var server = app();
server.use(app.static(staticDir))
server.listen(webPort)

Express over HTTPS (without Static Directory)

const app = require('express')();
const https = require('https');
const server = https.createServer(
        {
        key: fs.readFileSync('server.key'),
        cert: fs.readFileSync('server.cert')
        },
        app
    );
server.listen(APIPort);

When I try combining the two approaches, I get stuck because the static example bypasses createServer, and yet createServer is the crux of getting to HTTPS in the examples.

I'm sure the answer is simple, but I cannot arrive at or locate the solution.

crosen9999
  • 823
  • 7
  • 13

1 Answers1

1

Could you try the below code-snippet and see if it works for you?

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

const app = express();
app.use(express.static(process.env.SERVE_DIRECTORY));

app.get('/', function(req, res) {
    return res.end('Serving static files!');
});

const key = fs.readFileSync(__dirname + '/selfsigned.key');
const cert = fs.readFileSync(__dirname + '/selfsigned.crt');

const options = {
    key: key,
    cert: cert
};

const server = https.createServer(options, app);

server.listen(PORT, () => {
    console.log(`Serving on port ${PORT}`);
});

Please make sure to do the suitable changes before running the above code.

Kartik Chauhan
  • 2,779
  • 5
  • 28
  • 39
  • 1
    Note to admins: I meant to edit my own original post, and accidentally tried to edit the solution. Please ignore the attempted edit, and you can delete this comment, as well. Thanks. – crosen9999 Jul 14 '20 at 08:43