1

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();
3
  • 1
    did you export the Server from Server.js? what does app.js say when you ask it to console.log(Server) Commented Nov 15, 2019 at 8:07
  • 1
    add module.exports = Server at the end of your Server.js code Commented Nov 15, 2019 at 8:08
  • Thanks @Krzysztof Krzeszewski and @ Banujan Balendrakumar it was that ! Commented Nov 15, 2019 at 8:09

2 Answers 2

5

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;
Sign up to request clarification or add additional context in comments.

Comments

2

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.