[英]Node.js config file for mysql DB
I have a small issue when setting up my config file. 设置配置文件时我遇到了一个小问题。 I'm sure this is something simple but I don't see what is the problem.
我确信这很简单,但我不明白这是什么问题。
I have my config file config.js under config/config.js 我在config / config.js下有配置文件config.js
var databaseOptions = {
host : 'localhost',
database : 'test',
user : 'root',
password : 'root',
port : '8889'
};
module.exports = databaseOptions;
And then I use it in my model: 然后我在我的模型中使用它:
var config = require('../config/config.js');
var mysql = require('mysql');
var connection = mysql.createConnection(config.databaseOptions);
But it doesn't work ... Instead I get an error : TypeError: Cannot read property 'host' of undefined 但它不起作用......相反我得到一个错误: TypeError:无法读取未定义的属性'host'
I also tried like this : 我也尝试过这样:
var connection = mysql.createConnection({
host : config.databaseOptions.host,
database : config.databaseOptions.database,
user : config.databaseOptions.user,
password : config.databaseOptions.password,
port : config.databaseOptions.port
});
... but I still get an undefined error. ...但我仍然得到一个未定义的错误。
Any idea ...? 任何想法 ...?
You are exporting databaseOptions
directly so you just need: 您正在直接导出
databaseOptions
,因此您只需要:
var databaseOptions = require('../config/config.js');
var connection = mysql.createConnection(databaseOptions);
If you want to use config.databaseOptions, you need to export: 如果要使用config.databaseOptions,则需要导出:
var databaseOptions = {
host : 'localhost',
database : 'test',
user : 'root',
password : 'root',
port : '8889'
};
module.exports = {databaseOptions: databaseOptions} ;
or 要么
module.exports.databaseOptions = {
host : 'localhost',
database : 'test',
user : 'root',
password : 'root',
port : '8889'
};
Then you can use: 然后你可以使用:
var config = require('../config/config.js');
var connection = mysql.createConnection(config.databaseOptions);
The second way will be more flexible if you have more than one object you want to export from config
. 如果您要从
config
导出多个对象,则第二种方式将更灵活。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.