javascript 引用错误:nodejs中未定义连接

thtygnil  于 2022-11-27  发布在  Java
关注(0)|答案(1)|浏览(175)

两个.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;
vnzz0bqm

vnzz0bqm1#

尝试关闭回调函数内的连接

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
};

相关问题