Javascript 节点MySQL-可重用连接模块

Javascript 节点MySQL-可重用连接模块,javascript,mysql,node.js,database-connection,node-mysql,Javascript,Mysql,Node.js,Database Connection,Node Mysql,问题更新: 解决方案应详细说明节点连接模块的简化、适当模型,允许需要连接到数据库的节点应用程序的任何模块重用连接。这样,该问题对于节点中存在连接模块问题的任何人都可能有用 答案甚至可能包括一种传递不同凭据的方法,以便通过单个函数调用从应用程序中的任何位置连接到不同的表或数据库 我编写了一个脚本,它使用了许多简单的模块,允许用户发布登录数据,在服务器上验证这些数据,如果正确,则接收成功响应。一个非常基本的登录功能 问题是:一个用户可以登录,但在我重新启动服务器之前,任何登录尝试都无法连接到数据库

问题更新:

解决方案应详细说明节点连接模块的简化、适当模型,允许需要连接到数据库的节点应用程序的任何模块重用连接。这样,该问题对于节点中存在连接模块问题的任何人都可能有用

答案甚至可能包括一种传递不同凭据的方法,以便通过单个函数调用从应用程序中的任何位置连接到不同的表或数据库

我编写了一个脚本,它使用了许多简单的模块,允许用户发布登录数据,在服务器上验证这些数据,如果正确,则接收成功响应。一个非常基本的登录功能

问题是:一个用户可以登录,但在我重新启动服务器之前,任何登录尝试都无法连接到数据库

看起来,因为我在模块db_connect中的一个变量中声明了连接,并且需要该模块,所以该连接不能重复使用。它是在必需的模块中声明的,我错误地认为在每次连接尝试中调用变量会重新创建连接。没有

解决方案:正如barry在评论中所建议的,在db_connect模块中,我需要将连接功能设置为函数而不是变量,这样我就可以从验证脚本中创建连接

我该怎么做?我试图在调用createConnection函数时输出connection对象,createConnection函数是db_connect的导出方法

db_连接:

验证器:

控制台日志最初出现连接错误,但在我尝试修复后,错误与方法有关:


你的问题主要是我在评论中提到的,所以我会给出答案。别打你的额头伤了自己。:-请参阅下面我的内联评论。您有一个方法调用过多,结果未返回,变量命名错误-否则,它工作正常

db_connect.js

validator.js

如果你做了这两个和三个改变,你应该很乐意去做。和以往一样,如果有帮助,请随时要求澄清

更新这是我怎么称呼它的-正如你所看到的,我曾经让它尝试过2秒钟

jt-test.js

结果

等等。它无限期地运行。这三个文件的完整代码在

中。您可以签出我的emysql包


也许最近的node-mysql包有些过时,但仍然可以正常工作。

Make var-connection=login.connection;验证函数的第一行,而不是将其作为一次性初始化代码。Ahh。无法再次打开连接可能是个问题…已更改此设置。还是错误@barry Johnson啊-我没有足够仔细地阅读你的db_connect,很抱歉关于红鲱鱼的建议。问题仍然和我想的一样-您正在破坏在db_connect中仅创建一次的连接,因此无法重用它。各种各样的寻址方法,但代码中最快的方法是使db_connect.connection成为一个获得新mysql连接的函数。然后在主代码中,执行connection=login.connection以每次获得一个新连接。让我知道这是否有意义。如果您需要进一步的指导,我可以发布更明确的答案。@barry johnson我这样做了,但现在我将login.connection作为一个函数。。。如果对象是函数,如何访问该对象的connect方法?进行了以下更改。现在回到第一步。第二次尝试失败。C:\xampp\htdocs\officeball\node\u scripts>node index.js应用程序初始化服务器模块初始化登录模块初始化验证程序模块初始化db\u连接模块初始化销售模块初始化服务器运行于http://127.0.0.1:8080/ 用户username1正在尝试登录。。。与Officeball MySQL数据库的连接已打开。。。与Officeball MySQL数据库的连接已关闭。用户username1已成功登录。用户username1正在尝试登录。。。用户username1触发的错误:错误:无法连接。请公布您如何调用它。在昨晚回答之前,我通过两个连接进行了测试。看上面的更新。我在这里叫它-不知怎么的,这是错的吗?它只是好的,除了它根本不工作的事实。loginFail在哪里?登录在哪里?login.js怎么样?应该知道server.js中定义的应用程序?验证器包括在哪里?老实说,我是想帮你,但当我要求你的代码,而你却上传了一些甚至没有运行的东西时,这是相当令人沮丧的。我再次修复了您的代码并将其添加到。我把它改为GET而不是POST,因为我不可能浪费时间为它制作表单。
console.log('db_connect module initialized');
var mysql      = require('mysql');

function createConnection(){
    var connection = mysql.createConnection({
        host     : 'localhost',
        user     : 'root',
        password : '',
        database : 'officeball'
    });
}

exports.createConnection = createConnection();
exports.mysql = mysql;
console.log('validator module initialized');
var connect = require("./db_connect");

function validate(username, password, callback){

    var createConnection = connect.createConnection();
    //the idea is for this to return the object, connection, 
    //which opens a new connection

    connection.connect(function (err){
        if (err) return callback(new Error('Failed to connect'), null);
        console.log('Connection with the Officeball MySQL database openned...');

        connection.query('select username,password,fname,lname,rank,active from users where username=?',
                username,
                function(err,rows,fields) {
                    connection.destroy();
                    console.log('...Connection with the Officeball MySQL database closed.');
                    if (err)
                        return callback(new Error ('Error while performing query'), null);
                    if (rows.length !== 1)
                        return callback(new Error ('- [Anomaly] - Failed to find exactly one user'), null);

                    if (rows[0].password === password & rows[0].active === "yes") {

                        var result = new Object;

                        result.username = rows[0].username;
                        result.password = rows[0].password;
                        result.fname = rows[0].fname;
                        result.lname = rows[0].lname;
                        result.rank = rows[0].rank;

                        return callback(null, result);

                    } if(rows[0].active !== "yes"){

                        return callback(new Error ('User account not active.'), null);

                    }else {

                        return callback(new Error ('Login credentials did not match.'), null);

                    }

                });


    });
};

exports.validate = validate;
C:\xampp\htdocs\officeball\node_scripts>node index.js
application initialized
server module initialized
login module initialized
validator module initialized
db_connect module initialized
sale module initialized
Server running at http://127.0.0.1:8080/
User username1 is attempting login...
TypeError: Property 'createConnection' of object #<Object> is not a function
    at Object.validate (C:\xampp\htdocs\officeball\node_scripts\custom_modules\v
alidator.js:6:33)
    at C:\xampp\htdocs\officeball\node_scripts\custom_modules\login.js:61:13
    at callbacks (C:\xampp\htdocs\officeball\node_scripts\node_modules\express\l
ib\router\index.js:164:37)
    at param (C:\xampp\htdocs\officeball\node_scripts\node_modules\express\lib\r
outer\index.js:138:11)
    at pass (C:\xampp\htdocs\officeball\node_scripts\node_modules\express\lib\ro
uter\index.js:145:5)
    at Router._dispatch (C:\xampp\htdocs\officeball\node_scripts\node_modules\ex
press\lib\router\index.js:173:5)
    at Object.router (C:\xampp\htdocs\officeball\node_scripts\node_modules\expre
ss\lib\router\index.js:33:10)
    at next (C:\xampp\htdocs\officeball\node_scripts\node_modules\express\node_m
odules\connect\lib\proto.js:193:15)
    at multipart (C:\xampp\htdocs\officeball\node_scripts\node_modules\express\n
ode_modules\connect\lib\middleware\multipart.js:93:27)
    at C:\xampp\htdocs\officeball\node_scripts\node_modules\express\node_modules
\connect\lib\middleware\bodyParser.js:64:9
console.log('db_connect module initialized');
var mysql      = require('mysql');

function createConnection(){
    var connection = mysql.createConnection({
        host     : 'localhost',
        user     : 'root',
        password : '',
        database : 'officeball'
    });
    // ************ NOTE BELOW FOR CHANGE **************
    // You didn't return anything from this function. You need to return the connection
    return connection;
}
// ************ NOTE BELOW FOR CHANGE **************
// You are exporting a single connection by invoking createConnection();
// exports.createConnection = createConnection();
// what you want is:
exports.createConnection = createConnection;
exports.mysql = mysql;
function validate(username, password, callback){
    // ************ NOTE BELOW FOR CHANGE **************
    // You had:
    // var createConnection = connect.createConnection();
    // but based on your code, you wanted to write this instead:
    var connection = connect.createConnection();

    /// ... REMAINDER OMITTED, because it was A-OK and this is already a long page
};
var v = require('./validator');
var timers = require('timers');
var connections = 0;

timers.setInterval(function(){
    v.validate('bagehot','foo',function(err,result){
        if (err)
            console.log('failed', err);
        else
            console.log('success! ',result);
    });
},2000);
Connection with the Officeball MySQL database openned...
...Connection with the Officeball MySQL database closed.
success!  { username: 'bagehot',
  password: 'foo',
  fname: 'walter',
  lname: 'bagehot',
  rank: 12 }
Connection with the Officeball MySQL database openned...
...Connection with the Officeball MySQL database closed.
success!  { username: 'bagehot',
  password: 'foo',
  fname: 'walter',
  lname: 'bagehot',
  rank: 12 }
Connection with the Officeball MySQL database openned...
...Connection with the Officeball MySQL database closed.
success!  { username: 'bagehot',
  password: 'foo',
  fname: 'walter',
  lname: 'bagehot',
  rank: 12 }
Connection with the Officeball MySQL database openned...
...Connection with the Officeball MySQL database closed.
success!  { username: 'bagehot',
  password: 'foo',
  fname: 'walter',
  lname: 'bagehot',
  rank: 12 }