簡體   English   中英

TypeError: is not a constructor with Node and Express JS

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM