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 toconsole.log(Server)
– Krzysztof Krzeszewski Commented Nov 15, 2019 at 8:07 -
1
add
module.exports = Server
at the end of yourServer.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
2 Answers
Reset to default 5You 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
}