ReferenceError:nodejs中未定义连接

时间:2015-10-30 20:50:50

标签: javascript node.js

两个.js文件都在同一个文件夹中。我正在尝试运行该应用程序,但我收到user.js中未定义连接。它位于连接上调用查询的行上,表示它未定义。

index.js

var exports = module.exports = {};

var user = require('./user');

exports.User = user;
exports.startCon = startCon;

var mysql = require('mysql2');

function startCon() {
    return mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: 'root',
        database: 'users'
    })
}

user.js的

var dal = require('./index');

function User(){
    this.connection = null;
}

User.prototype.getAll = function(cb){
      this.connection = dal.startCon();

      connection.query('SELECT * FROM user;', function (error, data) {
        if(!error){
                cb(null, data);
        }
        else {
                console.log("Error Selecting : %s ", error );
                cb(error);
        }
    });

    connection.end();
}

module.exports = User;

1 个答案:

答案 0 :(得分:0)

尝试在回调函数内部关闭连接

callback() {
    connection.close()
}
  

这个模块真的很奇怪

您需要在函数内部构造连接实例

var mysql = require('mysql');

let doSmth = function(userId) {

    let connection = mysql.createConnection({
        host     : 'localhost',
        user     : 'root',
        password : '',
        database : 'test'
    });
        return new Promise((resolve, reject) => {

        connection.query({
                sql: 'SELECT `address` FROM `User` WHERE `user_id` = ?'
            },
            [userId],
            function (error, results, fields) {
                console.log(error, results)
                if(!error) {
                    var obj = JSON.parse(JSON.stringify(results));
                    resolve(obj)
                } else {
                    reject(error)
                }
            }
        );
    })
}
module.exports = {
    doSmth
};