“Home”不是Node JS上的构造函数

vshtjzan  于 5个月前  发布在  Node.js
关注(0)|答案(1)|浏览(41)

我使用consign来自动加载我的应用程序模型,路由等.我有一个模型,是建模在ES6风格,当我instanciate她它扔给我这个错误TypeError: app.src.models.Home is not a constructor我已经尝试使用ES5风格,但没有区别.对象,consign创建的模型是在里面,但我不能访问然后.
这是我的课:

/*function Home() {

}

Home.prototype.getHomeData = function (conexao, callback) {
    conexao.query('select * from tarefas', callback)
} //IT does not work like the item below, so I will keep using ES6
*/

class Home {
    constructor() {
        console.log('Construi')
    }

    getHomeData(conexao, callback) {
        conexao.query('select * from tarefas', callback)
    }
}
module.exports = function () {
    return Home
}

字符串
看:Server.js:

var express = require('express'),
    bodyparser = require('body-parser'),
    app = express();
var consign = require('consign');
consign()
    .include('./src/routes')
    .then('./src/config/db.js')
    .then('./src/models')
    .into(app);
console.log("I'm on server.js: ", app.src.models)
app.use(bodyparser.urlencoded({ extended: true }));
app.listen(3000, function () {
    console.log("Servidor ON");
});
module.exports = app;


控制台正确返回I'm on server.js: { 'home.model': [Function: Home] }
当我从路由中获取时,它一直显示app.src.models有数据,控制台输出:I'm on the home.js and still have data + { 'home.model': [Function: Home] }
但是当我尝试示例化类时,我抛出了上面引用的错误.

module.exports = function (app) {
    app.get('/', function (req, res) {

       console.log("I'm on the home.js and still have data +", app.src.models)
        var conexao = app.src.config.db()
        var homeData = new app.src.models.Home();

        homeData.getHomeData(conexao, (err, result) => {
            if (err) {
                res.json(err)
            } else {
                res.json(result)
            }
        })
    });
}


如果我尝试下面的控制台得到未定义:

console.log("I'm on the home.js and still have data +", app.src.models.Home)


这是我的回购,如果你想要https://github.com/tiagosilveiraa/PM_API
试验1:
在类Home中,我创建了module.exports = new Home(),它抛出了相同的错误

aiqt4smr

aiqt4smr1#

导出您的Home类如下:

module.exports = { Home };

字符串
并导入/使用如下:

const { Home } = require('path/to/Home.js');
const home = new Home();
home.getHomeData(...)

相关问题