【发布时间】:2019-08-20 23:58:50
【问题描述】:
我正在使用 consign 从我的 Node JS api 上的模块进行自动加载,在此我加载我的所有路由、模型和我的数据库连接函数,当我运行 nodemom app 时,会加载建立连接的模块但是我无法连接到数据库,他向我抛出了这个错误TypeError: Cannot read property 'db' of undefined
看看我的树文件:
我可以加载路线因为
db.js(具有数据库配置的文件)
var mysql = require('mysql');
var connMySQL = function () {
console.log("I've Started the connection")
return mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'agimplant'
});
}
module.exports = function () {
console.log("I've loaded this function")
return connMySQL;
}
服务器.js
var express = require('express'),
bodyparser = require('body-parser'),
consign = require('consign'),
app = express();
consign()
.include('./src/routes')
.then('./src/config/db.js')
.then('./src/models')
.into(app);
app.use(bodyparser.urlencoded({ extended: true }));
app.listen(4000, function () {
console.log("Servidor ON");
});
module.exports = app;
Home.route.js 上的连接调用
module.exports = function (app) {
app.get('/', (req, res) => {
console.log("Call the Connection Here")
var connection = app.config.db();
});
}
【问题讨论】:
-
app.config必须是未定义的 - 你在哪里给它赋值了? -
如果使用 MAMP,请确保任何计算机用户都可以发现您的数据库,并设置端口选项。
-
@JaromandaX,我已经完成了托运,这里是 .then('./src/config/db.js')
-
@Raymond 我试图连接到其他数据库,它会抛出同样的错误,我有其他可以正常连接的应用程序。
-
@JaromandaX 对不起,但我不明白.. 如果它什么也没做,我怎么能给配置赋值?谢谢!
标签: javascript mysql node.js node-modules ecmascript-5