我正在使用委托来自动加载我的应用程序模型,路线等...我有一个正在以ES6样式建模的模型,当我实例化它时,抛出此错误TypeError: app.src.models.Home is not a constructor
我尝试使用ES5样式,但没有区别。委托人创建的对象带有内部模型,但那时我无法访问。
那是我的课程:
/*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:
在课堂上我做了module.exports = new Home()
,它抛出了相同的错误
答案 0 :(得分:2)
以这种方式导出Home类:
module.exports = { Home };
并这样导入/使用它:
const { Home } = require('path/to/Home.js');
const home = new Home();
home.getHomeData(...)