javascript - 类型错误 : is not a constructor with Node and Express JS

标签 javascript node.js express

我在下面编写了代码,但出现了 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 类。在您的“Server.js”文件中,执行此操作:

export default Server {
...
}

然后像这样留下你的“app.js”:

const Server = require("./Server");

上述方法只适用于 ES6 及以上版本,如果不使用 ES6:

class Server {
...
}

module.exports = Server;

关于javascript - 类型错误 : is not a constructor with Node and Express JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58872652/

相关文章:

javascript - "this"在 ngOnInit 中变为未定义

javascript - 两个日期之间的确切月份差异 - MomentJS

node.js - 使用 Google oauth 访问时创建与登录

node.js - 检查空值快速验证器

javascript - 如果在一定时间内未单击按钮,如何隐藏元素

javascript - OnClick 在 Ios11 上不起作用

javascript - 当字符少于 3 个时禁用 HTML 按钮

mysql - Nodejs mysql 和 mysql2 驱动程序的咨询锁返回 null

node.js - 当请求超时时,如何停止 Express 中的进程?

javascript - 客户端发送值到node.js并设置为cookie