Node.js mysql 数据库的配置文件

Node.js config file for mysql DB

我在设置配置文件时遇到了一个小问题。我确定这很简单,但我看不出有什么问题。

我的配置文件 config.js 在 config/config.js

var databaseOptions = {
    host     : 'localhost',
    database : 'test',
    user     : 'root',
    password : 'root',
    port     : '8889'
};
module.exports = databaseOptions;

然后我在我的模型中使用它:

var config = require('../config/config.js');
var mysql = require('mysql');
var connection = mysql.createConnection(config.databaseOptions);

但是没用... 相反,我得到一个错误:TypeError: Cannot read 属性 'host' of undefined

我也这样试过:

var connection = mysql.createConnection({
          host     : config.databaseOptions.host,
          database : config.databaseOptions.database,
          user     : config.databaseOptions.user,
          password : config.databaseOptions.password,
          port     : config.databaseOptions.port
});

...但我仍然收到未定义的错误。

有什么想法...?

您正在直接导出 databaseOptions,因此您只需要:

var databaseOptions = require('../config/config.js');
var connection = mysql.createConnection(databaseOptions);

如果要使用config.databaseOptions,需要导出:

var databaseOptions = {
    host     : 'localhost',
    database : 'test',
    user     : 'root',
    password : 'root',
    port     : '8889'
};
module.exports = {databaseOptions: databaseOptions} ;

module.exports.databaseOptions = {
  host     : 'localhost',
  database : 'test',
  user     : 'root',
  password : 'root',
  port     : '8889'
};

那么你可以使用:

var config = require('../config/config.js');
var connection = mysql.createConnection(config.databaseOptions);

如果您要从 config 中导出多个对象,则第二种方法会更加灵活。