【问题标题】:Error: Can't add new command when connection is in closed state错误:连接处于关闭状态时无法添加新命令
【发布时间】:2019-09-14 11:49:45
【问题描述】:

我最近在实时服务器上部署了我的 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;

【问题讨论】:

  • 我们需要更多代码。你是如何查询数据库的?你的哪一行代码抛出了错误?
  • 您是否在localhost 中运行了关于您的Node.js 应用程序所在位置的mysql?
  • ETIMEDOUT 通常在服务器未运行或由于防火墙问题(或任何网络可访问性问题)时发生

标签: node.js express mysql2


【解决方案1】:

我遇到了类似的问题,最终不得不将连接请求放在它自己的 .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();
        }
    });
},

【讨论】:

    猜你喜欢
    • 2018-05-12
    • 2022-07-06
    • 1970-01-01
    • 2019-02-08
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    相关资源
    最近更新 更多