【问题标题】:Getting undefined on try to connect mysql with node js using consign尝试使用 consign 将 mysql 与节点 js 连接时未定义
【发布时间】: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


【解决方案1】:

正如在 src 补丁的交付中所讨论的,将 app.src.conf 用于调用您的对象。 始终将 src 用于方法访问,并从调试中使用 console.log,这很棒

【讨论】:

    猜你喜欢
    • 2017-06-24
    • 1970-01-01
    • 2020-03-08
    • 1970-01-01
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-15
    相关资源
    最近更新 更多