MissKnacki
MissKnacki

Reputation: 279

TypeError: is not a constructor with Node and Express JS

I wrote code below and I have a TypeError: Server is not a constructor and I don't see why and how to fixe it.

Server.js code :

const express = require('express');

class Server {
    constructor() {
        this.app = express();

        this.app.get('/', function(req, res) {
            res.send('Hello World');
        })
    }

    start() {
        this.app.listen(8080, function() {
            console.log('MPS application is listening on port 8080 !')
        });
    }
}

app.js code :

const Server = require('./Server');
const express = require('express');

const server = new Server();

server.start();

Upvotes: 1

Views: 4939

Answers (2)

BadPiggie
BadPiggie

Reputation: 6359

You need to export your class before import anywhere,

Add the following line at the end of your Server.js

module.exports = Server

ES6

export default Server {
 // you implementation
}

Upvotes: 2

SteapStepper69
SteapStepper69

Reputation: 1295

You did not export the Server class. In your 'Server.js' file, do this:

export default Server {
...
}

and leave your 'app.js' like this:

const Server = require("./Server");

The above method only works with ES6 and up, if not using ES6:

class Server {
...
}

module.exports = Server;

Upvotes: 5

Related Questions