[英]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.我在下面写了代码,我有一个TypeError: Server is not a constructor
,我不明白为什么以及如何修复它。
Server.js code: Server.js 代码:
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: app.js 代码:
const Server = require('./Server');
const express = require('express');
const server = new Server();
server.start();
You did not export the Server
class.您没有导出Server
class。 In your 'Server.js' file, do this:在您的“Server.js”文件中,执行以下操作:
export default Server {
...
}
and leave your 'app.js' like this:并像这样留下您的“app.js”:
const Server = require("./Server");
The above method only works with ES6 and up, if not using ES6:如果不使用 ES6,上述方法仅适用于 ES6 及更高版本:
class Server {
...
}
module.exports = Server;
You need to export
your class before import anywhere,您需要在任何地方导入之前export
class,
Add the following line at the end of your Server.js
在Server.js
的末尾添加以下行
module.exports = Server
ES6 ES6
export default Server {
// you implementation
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.