Pass Express function to another file which calls HTTPS createServer

Viewed 95

According to Node Best Practices, it's recommended to separate the HTTP and Express server API.

My issue is that createServer expects a function as the second argument but I am passing in an object.

app.js

const config = require('./config');
const express = require('express');
const app = express();

app.use(express.static(__dirname + config.STATIC_DIR));
app.use(express.json());

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

// POST /agent used for registration requests
app.post('/agent', (req, res) => {
  console.log('Received registration request from ', req.body);
  return res.send('Received a POST HTTP method');
});

server.js

const fs = require('fs');
const config = require('./config');
const mysql = require('mysql2/promise');
const app = require('./app');

const sslConfig = {
  key: fs.readFileSync(config.SSL_KEY),
  cert: fs.readFileSync(config.SSL_CERT)
};

const server = require('https').createServer(sslConfig, app);
const io = require('socket.io')(server);

I get the following error:

 throw new errors.ERR_INVALID_ARG_TYPE('listener', 'Function', listener);
    ^

TypeError [ERR_INVALID_ARG_TYPE]: The "listener" argument must be of type Function. Received type object
    at checkListener (events.js:55:11)
    at _addListener (events.js:214:3)
    at Server.addListener (events.js:272:10)
    at new Server (https.js:67:10)
    at Object.createServer (https.js:85:10)
    at Object.<anonymous> (/Users/Code/server.js:18:8)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)

What changes are required if I want to pass an SSL configuration into the createServer method?

1 Answers

I was able to fix the issue by adding the following line at the end of app.js:

module.exports = app;
Related