Nodejs MySQL连接超时

时间:2016-11-25 15:37:57

标签: node.js

当我运行该应用程序时,它会显示Database is connected!

db.js

var mysql = require('mysql');
var settings = require('./config');
var db;
var exports = {};

exports.connectdb = function () {

 db = mysql.createConnection(settings.Database);

 db.connect(function(err){

     console.log('connecting');
     if(!err) {
         console.log('Database is connected!');
         return db;
     } else {
         console.log('Error connecting database!'+err);
         return null;
     }
 });

};

module.exports = exports;

但是当我尝试从user.js连接数据库时,它会显示connection is null / TypeError: Cannot read property 'query' of undefined

来自 user.js

代码块

var exports = {};
var dbcon = require('../config/db.js');
var dbconn = dbcon.connectdb();

exports.login = function(email,password) {

var userdetails = { name:email, password:password};

var dbconn = dbcon.connectdb();
if ( dbconn == null ) console.log('still nul');


dbconn.query("SELECT * FROM users where email = '"+email+"' and password = '"+password +"'", function (err, result) {
    if(err)
    {
        console.log(result[0]+' err');
        return null;
    }
});
};

module.exports = exports;

1 个答案:

答案 0 :(得分:2)

Node.js本质上是异步的。您正试图以同步方式使用它。要使其工作,您必须使用回调模式。以下是一个例子:

<强> db.js

var mysql = require('mysql');
var settings = require('./config');
var exports = {};

exports.connectdb = function (callback) {

 var db = mysql.createConnection(settings.Database);

 db.connect(function(err){
     callback(err,db);
 });

};

module.exports = exports;

<强> user.js的

var exports = {};
var dbcon = require('../config/db.js');

exports.login = function(email,password) {

    var userdetails = { name:email, password:password};

    dbcon.connectdb(function(err, dbconn){
        if ( err) //handle error


        dbconn.query("SELECT * FROM users where email = '"+email+"' and password = '"+password +"'", function (err, result) {
        if(err)
        {
           console.log(result[0]+' err');
        }
        });
    });
};

module.exports = exports;

从上面的代码中,您可以看到connectdb函数如何接受函数回调。连接数据库时,代码将执行该回调以发送结果。在user.js文件中,您现在可以传递回调函数并使用它为您提供的结果(数据库)。您可以找到有关Node.js'asynchronous nature here的更多信息。基本上,异步代码使用回调,同步代码使用return语句。从异步函数返回值将总是产生null结果,因为异步回调将始终在调用函数后“某个时间”触发。