解决 node-mysql 初始化错误?

Solving node-mysql initialization errors?

我正在尝试使用可以在 here 中找到的 node-mysql 模块。我以前用过这个没有任何问题,但在最近的一个项目中遇到了一个奇怪的问题,它永远无法连接到数据库。我知道我的登录凭据是正确的,因为它们通过正常的 MySQL 命令行工作。

但是,当 node-mysql 模块尝试连接时,我总是会收到错误消息。这是我到目前为止的代码,启用了 debugging

var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : 'password',
    database : 'Coachletic',
    pool     : { maxConnections: 50, maxIdleTime: 30},
    debug    : true
});

connection.connect(function(err){
    if(!err) {
        console.log("MySQL Database is connected.");
    } else {
        console.log(err);
        console.log("Error connecting to MySQL Database.");  
    }
});

global.connection = connection;

这是控制台的输出:

<-- HandshakeInitializationPacket
HandshakeInitializationPacket {
  protocolVersion: 10,
  serverVersion: '5.6.19-0ubuntu0.14.04.1',
  threadId: 64,
  scrambleBuff1: <Buffer 65 3f 48 2e 4d 78 38 49>,
  filler1: <Buffer 00>,
  serverCapabilities1: 63487,
  serverLanguage: 8,
  serverStatus: 2,
  serverCapabilities2: 32895,
  scrambleLength: 21,
  filler2: <Buffer 00 00 00 00 00 00 00 00 00 00>,
  scrambleBuff2: <Buffer 47 68 54 4e 6b 4e 25 6a 6a 54 46 42>,
  filler3: <Buffer 00>,
  pluginData: 'mysql_native_password',
  protocol41: true }

--> ClientAuthenticationPacket
ClientAuthenticationPacket {
  clientFlags: 455631,
  maxPacketSize: 0,
  charsetNumber: 33,
  filler: undefined,
  user: 'root',
  scrambleBuff: <Buffer 40 de 4c 94 3b c4 6f 15 0d 1c 49 12 04 46 af 64 d9 4d 41 76>,
  database: 'Coachletic',
  protocol41: true }

{ [Error: Handshake inactivity timeout]
  code: 'PROTOCOL_SEQUENCE_TIMEOUT',
  fatal: true,
  timeout: undefined }
Error connecting to MySQL Database.

尝试搜索此错误的解决方案,但没有找到任何有用的方法。

这是适合我的代码:

初始化

var mysql = require('mysql');
var pool = mysql.createPool({
    host: 'XXX.XXX.XXX.XX',
    user: 'xxxxx_xxx',
    password: 'xxxxxxxxx',
    database: 'xxxxxxx'
});

用法

pool.getConnection(function (err, connection) {
    connection.query('MY SQL QUERY', function (err, result) {
        connection.release();
    });

让我知道它是否适合你。

在进行更多挖掘后,发现这是与 Node 4.2.0 相关的问题。这是参考线程:https://github.com/felixge/node-mysql/issues/1236

修复涉及将 lib/protocol/sequences/Sequence.js 文件中的 this._idleTimeoutundefined 更改为 -1

问题是节点 4.2.0 和节点-mysql。

提到一个快速简单的修复,对于那些遇到这个问题并且不关心节点版本并想要快速修复的人,只需为您的机器强制使用以前的节点版本 (4.1.2) 就可以了不会坏的。例如,对于 heroku 用户,这可以通过添加到 package.json 作为主要 json 对象的一部分来实现: "engines":{ "node": "4.1.2" }