简体   繁体   中英

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();

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;

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM