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