当用户登录系统时,我是从前端获取数据库名称的,我必须与该数据库建立连接以进行进一步的处理。如果在同一页面上创建连接,我可以做到这一点,但我想使用'exports'
我正在尝试这个。我是node.js的新手,所以如果有一些非常愚蠢的错误,请不要介意并帮助我理解。
我尝试了其他导出方式,但无法使其运行。
我的DB_dynamic.js:
var mysql = require('mysql');
exports.dynamicConnection= function(dbname){
var connection = mysql.createConnection({
host: process.env.DBHost || 'localhost',
port: process.env.DBPort || 3306,
user: process.env.DBUser || 'root',
password: process.env.DBPassword || '',
database: process.env.DBName || dbname
});
connection.connect((err) =>{
if(err) throw err;
console.log('Mysql Connected...');
});
}
现在在我的model.js中
var new_conn = require('./DB_dynamic.js');
var conn = new_conn.dynamicConnection(dbname);
conn.query("my query"); //Error!
错误:
TypeError: Cannot read property 'query' of undefined
答案 0 :(得分:1)
DB_dynamic.js
const mysql = require('mysql');
module.exports = dbConnection = (dbname) => {
return connection = mysql.createConnection({
host: process.env.DBHost || 'localhost',
port: process.env.DBPort || 3306,
user: process.env.DBUser || 'root',
password: process.env.DBPassword || '',
database: process.env.DBName || dbname
});
};
model.js
let dbConnection = require('./DB_dynamic.js');
console.log(dbConnection("your_db_name").query("your_query"))
答案 1 :(得分:0)
module
。exports.dynamicConnection = function(dbname){