我使用NodeJS与express,consign,body-parser等。
我试图在var中加载模块,所以我可以使用它们的功能,但我得到了:
TypeError: Cannot read property 'listar' of undefined
at app.get (/home/sartori/Documentos/Projetos/react-system/api/controllers/autores.js:6:11)
at Layer.handle [as handle_request] (/home/sartori/Documentos/Projetos/react-system/api/node_modules/express/lib/router/layer.js:95:5)
at next (/home/sartori/Documentos/Projetos/react-system/api/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/sartori/Documentos/Projetos/react-system/api/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/sartori/Documentos/Projetos/react-system/api/node_modules/express/lib/router/layer.js:95:5)
at /home/sartori/Documentos/Projetos/react-system/api/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/sartori/Documentos/Projetos/react-system/api/node_modules/express/lib/router/index.js:335:12)
at next (/home/sartori/Documentos/Projetos/react-system/api/node_modules/express/lib/router/index.js:275:10)
at /home/sartori/Documentos/Projetos/react-system/api/node_modules/express-validator/lib/express_validator.js:250:5
at Layer.handle [as handle_request] (/home/sartori/Documentos/Projetos/react-system/api/node_modules/express/lib/router/layer.js:95:5)
这是我的控制人员:
module.exports = app => {
app.get('/api/autores', (req,res) => {
let connection = app.connection.connectionFactory();
let autores = app.models.AutoresDao(connection);
autores.listar((error,result) => {
if(error) {
console.log('Erro ao listar os autores: ' + error);
res.status(500).send(error);
} else {
res.json(result);
}
});
});
}
这是AutoresDao:
function AutoresDao(connection) {
this._connection = connection;
}
AutoresDao.prototype.listar = callback => this._connection.query('SELECT * FROM autores', callback);
module.exports = function() {
return AutoresDao;
}
问题是:无法读取属性' listar'未定义的。
显然问题是加载AutoresDao文件。
我100%确定文件路径,AutoresDao在模型文件夹中,已经加载到托运。对于控制器,连接,快速配置等也一样。
知道我做错了什么?
答案 0 :(得分:1)
如果要以这种方式格式化对象构造函数,则需要使用'new'关键字。您必须重新格式化AutoresDao函数以显式返回对象,或者在将其分配给控制器中的autores时使用“new”关键字。
请查看本文以获取不同实例化模式的说明。
https://medium.com/dailyjs/instantiation-patterns-in-javascript-8fdcf69e8f9b
希望有所帮助!欢呼声。