最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TypeError: is not a constructor with Node and Express JS - Stack Overflow

programmeradmin3浏览0评论

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

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();
Share Improve this question asked Nov 15, 2019 at 8:03 MissKnackiMissKnacki 2791 gold badge4 silver badges17 bronze badges 3
  • 1 did you export the Server from Server.js? what does app.js say when you ask it to console.log(Server) – Krzysztof Krzeszewski Commented Nov 15, 2019 at 8:07
  • 1 add module.exports = Server at the end of your Server.js code – BadPiggie Commented Nov 15, 2019 at 8:08
  • Thanks @Krzysztof Krzeszewski and @ Banujan Balendrakumar it was that ! – MissKnacki Commented Nov 15, 2019 at 8:09
Add a ment  | 

2 Answers 2

Reset to default 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;

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
}
发布评论

评论列表(0)

  1. 暂无评论