错误:连接处于关闭状态时无法添加新命令

时间:2019-04-25 05:53:40

标签: node.js express mysql2

我最近在实时服务器上部署了我的node.js API应用程序。我在实时服务器上遇到这些问题。

我已经用谷歌搜索了它,但没有任何确切的解决方案。谁能建议我该如何解决这个问题?

{ Error: read ETIMEDOUT at TCP.onread (net.js:622:25) errno: 'ETIMEDOUT', code: 'ETIMEDOUT', syscall: 'read', fatal: true }

 { Error: Can't add new command when connection is in closed state at PoolConnection._addCommandClosedState }

我像这样使用mysql连接池

var mysql = require('mysql2');
var mysqlPool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'xyz',
database: 'xyz',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
module.exports = mysqlPool;

1 个答案:

答案 0 :(得分:0)

我遇到了类似的问题,最终不得不将连接请求放入它自己的.js文件中,并将其导入到控制器中- connectionRequest.js

module.exports = function () {

    let mysql = require('mysql2')
    let connCreds = require('./connectionsConfig.json');

    //Establish Connection to the DB
    let connection = mysql.createConnection({
        host: connCreds["host"],
        user: connCreds['username'],
        password: connCreds['password'],
        database: connCreds['database'],
        port: 3306
    });

    //Instantiate the connection
    connection.connect(function (err) {
        if (err) {
            console.log(`connectionRequest Failed ${err.stack}`)
        } else {
            console.log(`DB connectionRequest Successful ${connection.threadId}`)
        }
    });

    //return connection object
    return connection
}

一旦完成,便可以将其导入控制器文件中的查询中,如下所示 ControllerFile.js

let connectionRequest = require('../config/connectionRequest')

controllerMethod: (req, res, next) => {
    //Establish the connection on this request
    connection = connectionRequest()

    //Run the query
    connection.query("SELECT * FROM table", function (err, result, fields) {
        if (err) {
            // If an error occurred, send a generic server failure
            console.log(`not successful! ${err}`)
            connection.destroy();

        } else {
            //If successful, inform as such
            console.log(`Query was successful, ${result}`)

            //send json file to end user if using an API
            res.json(result)

            //destroy the connection thread
            connection.destroy();
        }
    });
},