简体   繁体   中英

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

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

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:

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

If you want to use config.databaseOptions, you need to export:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM