Error cannot enqueue handshake after already enqueuing a handshake

function reloadQuestion() { var obj = {}; connection.connect(); connection.query("SELECT * FROM quiz", function (err, rows, fields) { if (err) throw err; for (var i = 0; i < rows.lengt...
function reloadQuestion() {
    var obj = {};
    connection.connect();
    connection.query("SELECT * FROM quiz", function (err, rows, fields) {
        if (err) throw err;
        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            obj = {"id":row.id, "question":row.question, "answers":row.answers.split(", ")};
            f100.push(obj);
            arr.push(i);
        };
        shuffleArray(arr);
        newQuestion();
    });
    connection.end();
}

reloadQuestion();

its work fine, then when after a condition when try to call reloadQuestion again its got error

Error: Cannot enqueue Handshake after already enqueuing a Handshake.
    at Protocol._validateEnqueue (/home/bot/node_modules/mysql/lib/protocol/Protocol.js:202:16)
    at Protocol._enqueue (/home/bot/node_modules/mysql/lib/protocol/Protocol.js:129:13)
    at Protocol.handshake (/home/bot/node_modules/mysql/lib/protocol/Protocol.js:52:41)
    at Connection.connect (/home/bot/node_modules/mysql/lib/Connection.js:123:18)
    at reloadQuestion (/home/bot/f100.js:56:13)
    at null._onTimeout (/home/bot/f100.js:80:8)
    at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)

already try to remove connection.end(); but the problem still

According to:

TL;DR You need to establish a new connection by calling the createConnection method after every disconnection.

and

Note: If you’re serving web requests, then you shouldn’t be ending connections on every request. Just create a connection on server
startup and use the connection/client object to query all the time.
You can listen on the error event to handle server disconnection and
for reconnecting purposes. Full code
here.


From:

  • Readme.md — Server disconnects:

    https://github.com/felixge/node-mysql#server-disconnects

It says:

Server disconnects

You may lose the connection to a MySQL server due to network problems,
the server timing you out, or the server crashing. All of these events
are considered fatal errors, and will have the err.code =
'PROTOCOL_CONNECTION_LOST'
. See the Error
Handling section for more information.

The best way to handle such unexpected disconnects is shown below:

function handleDisconnect(connection) {
  connection.on('error', function(err) {
    if (!err.fatal) {
      return;
    }

    if (err.code !== 'PROTOCOL_CONNECTION_LOST') {
      throw err;
    }

    console.log('Re-connecting lost connection: ' + err.stack);

    connection = mysql.createConnection(connection.config);
    handleDisconnect(connection);
    connection.connect();
  });
}

handleDisconnect(connection);

As you can see in the example above, re-connecting a connection is
done by establishing a new connection. Once terminated, an existing
connection object cannot be re-connected by design.

With Pool, disconnected connections will be removed from the pool
freeing up space for a new connection to be created on the next
getConnection call.


I have tweaked the function such that every time a connection is needed, an initializer function adds the handlers automatically:

function initializeConnection(config) {
    function addDisconnectHandler(connection) {
        connection.on("error", function (error) {
            if (error instanceof Error) {
                if (error.code === "PROTOCOL_CONNECTION_LOST") {
                    console.error(error.stack);
                    console.log("Lost connection. Reconnecting...");

                    initializeConnection(connection.config);
                } else if (error.fatal) {
                    throw error;
                }
            }
        });
    }

    var connection = mysql.createConnection(config);

    // Add handlers.
    addDisconnectHandler(connection);

    connection.connect();
    return connection;
}

Initializing a connection:

var connection = initializeConnection({
    host: "localhost",
    user: "user",
    password: "password"
});

Minor suggestion: This may not apply to everyone but I did run into a minor issue relating to scope. If the OP feels this edit was unnecessary then he/she can choose to remove it. For me, I had to change a line in initializeConnection, which was var connection = mysql.createConnection(config); to simply just

connection = mysql.createConnection(config);

The reason being that if connection is a global variable in your program, then the issue before was that you were making a new connection variable when handling an error signal. But in my nodejs code, I kept using the same global connection variable to run queries on, so the new connection would be lost in the local scope of the initalizeConnection method. But in the modification, it ensures that the global connection variable is reset This may be relevant if you’re experiencing an issue known as

Cannot enqueue Query after fatal error

after trying to perform a query after losing connection and then successfully reconnecting. This may have been a typo by the OP, but I just wanted to clarify.

Issue

I’m attempting to make two functions, one which retrives an object from an SQL database, the other which saves an object to the same SQL database. I am using node.js and mysql to do this. I have two functions, fetchEmployee and Employee.save, which fetch and save an employee respectively. When I call fetchEmployee, and the callback includes Employee.save, however, I get the error Cannot enqueue Handshake after already enqueuing a Handshake. Even weirder, Employee.save seems to run before the error is thrown.

EDIT: employee.save appearing to run is a symptom of async, as console.log("Saved!") is called before the callback function passed to SQL.parse This means the error appears during the parse. Further, if within parse console.log("connection created"); is added after con.connect, and console.log("Made it out."); is added after the end of con.connect, when calling Employee.save, the console outputs > "connection created", then throws the error, meaning the save query is never finished, but the error is thrown after con.connect

The Employee class is defined by the following

function Employee(obj) {
    /** Defines the Employee class
     * @arg obj.id : an integer; the employee's id
     * @arg obj.name : A string; the employee's name
     * @arg obj.position : A string; the employee's positions split by commas
     */

    this.id = obj.id;
    this.name = obj.name;
    this.position = obj.position;

    this.save = function() {
        SQL.parse({
            sql : `UPDATE EMPLOYEES
                SET id=?, name=?, position=?
                WHERE id=?`,
                replace_ : [this.id, this.name, this.position, this.id],
                result : false
        });
        console.log("Saved!");
    }
}

Note the console.log("Saved!");, as this comes up later

fetchEmployee is defined by this function:

function fetchEmployee(id, callback) {
    /** Fetch an employee from the employee table
     * @arg id : An integer; the id of the employee to fetch
     * @arg callback : A callback function to pass the employee to
     */

     SQL.parse({ // Perform the parse, define the sql, replace, and result
        sql : "SELECT * FROM employees WHERE id=?",
        replace_ : [id],
        result : true
     },

     function(err, data) {
         if(err) { // Pass an error if there's an error
             callback(err, null);
             throw err;
         }
         // Pass the employee to the callback as an employee object if there's no errors
         callback(null, new Employee({  // data is passed as a list from the sql table, so take only the object we need through [0]
                id : data[0].id,
                name : data[0].name,
                position : data[0].position
             })
         );
     });
}

Finally, SQL.parse is defined in this file:

var mySQL = require("mysql");

var con = mySQL.createConnection({ //Create connection
    host : "localhost",
    database : "testdb1",
    user : "root",
    password : "***************" 
});

function parse(obj, callback) {
    /** Parses an sql query. 
     * @arg callback : A callback function, will be passed the data
     * @arg obj.sql : an sql query
     * @arg obj.replace_ : A list of replacements for ?s in sql
     * @arg obj.result : a boolean indicating whether a result should be returned
     */

     //Assign meaningfull values
     obj.replace_ = obj.replace_ || [];
     callback = callback || function() {};

    con.connect(function(err) {
        if(err) throw err;

        //Connect and pass the sql command to the server
        con.query(obj.sql, obj.replace_, function(err, data) {
            if(err) { //Pass the err to the callback if there is an err
                callback(err, null);
                throw err;
            }
            else if(obj.result) { // Pass the data to the callback if result is true
                callback(null, data)
            }
        });
    });
}

module.exports = {
    parse : parse
};

When I call this block of code

fetchEmployee(985, function(err, data) {
    if(err) throw err;
    console.log(data);
    data.save();
});

The console outputs

Employee {
  id: 985,
  name: 'Skidd',
  position: 'Dishwasher, Busser',
  save: [Function] }
Saved!
Error: Cannot enqueue Handshake after already enqueuing a Handshake. [...]

It appears to me that it correctly runs fetchEmployee, as data is logged to the console correctly with the data of the employee. It then logs Saved!, seeming to indicate that Employee.save ran correctly, then after all the code is done, throws the error. I can’t for the life of me figure out why this would happen, here or on google or through testing.

I’ve tried to add con.end to the end of parse in sql.js, this changes the error to Cannot enqueue Handshake after invoking quit

Solution

I was able to solve this problem by placing

var con = mySQL.createConnection({ //Create connection
    host : "localhost",
    database : "testdb1",
    user : "root",
    password : "***************" 
});

inside of the parse function, though I’m not 100% sure why this worked.

Answered By – Travis

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Код:

var sql = require("mysql");
var connection = sql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'chat'
});

app.get('/', function(req, res) {
    connection.connect();
    var loga = "kulonful";
    connection.query('select * from users where login = "'+loga+'"', function(err, result){
        if(err) { connection.end(); res.send('Произошла критическая ошибка'); }
        connection.end();
        res.send(result);
    });
})

В первый раз всё гладенько, а если обновить страницу — в консоли выбивает ошибку:

events.js:160
throw er; // Unhandled ‘error’ event
^

Error: Cannot enqueue Handshake after invoking quit.
at Protocol._validateEnqueue (/root/node_modules/mysql/lib/protocol/Protocol.js:202:16)
at Protocol._enqueue (/root/node_modules/mysql/lib/protocol/Protocol.js:135:13)
at Protocol.handshake (/root/node_modules/mysql/lib/protocol/Protocol.js:52:41)
at Connection.connect (/root/node_modules/mysql/lib/Connection.js:130:18)
at /root/api.js:18:16
at Layer.handle [as handle_request] (/root/node_modules/express/lib/router/layer.js:82:5)
at next (/root/node_modules/express/lib/router/route.js:100:13)
at Route.dispatch (/root/node_modules/express/lib/router/route.js:81:3)
at Layer.handle [as handle_request] (/root/node_modules/express/lib/router/layer.js:82:5)
at /root/node_modules/express/lib/router/index.js:235:24

Что не так? Помогите)

events.js:160
      throw er; // Unhandled ‘error’ event
      ^

Error: Cannot enqueue Handshake after invoking quit.
    at Protocol._validateEnqueue (D:bookstorenode_modulesmysqllibprotocolProtocol.js:202:16)
    at Protocol._enqueue (D:bookstorenode_modulesmysqllibprotocolProtocol.js:135:13)
    at Protocol.handshake (D:bookstorenode_modulesmysqllibprotocolProtocol.js:52:41)
    at Connection.connect (D:bookstorenode_modulesmysqllibConnection.js:130:18)
    at D:bookstorebuilddev-server.js:50:14
    at Layer.handle [as handle_request] (D:bookstorenode_modules[email protected]@expresslibrouterlayer.js:95:5)
    at next (D:bookstorenode_modules[email protected]@expresslibrouterroute.js:137:13)
    at Route.dispatch (D:bookstorenode_modules[email protected]@expresslibrouterroute.js:112:3)
    at Layer.handle [as handle_request] (D:bookstorenode_modules[email protected]@expresslibrouterlayer.js:95:5)
    at D:bookstorenode_modules[email protected]@expresslibrouterindex.js:281:22
    at param (D:bookstorenode_modules[email protected]@expresslibrouterindex.js:354:14)
    at param (D:bookstorenode_modules[email protected]@expresslibrouterindex.js:365:14)
    at Function.process_params (D:bookstorenode_modules[email protected]@expresslibrouterindex.js:410:3)
    at next (D:bookstorenode_modules[email protected]@expresslibrouterindex.js:275:10)
    at Function.handle (D:bookstorenode_modules[email protected]@expresslibrouterindex.js:174:3)
    at router (D:bookstorenode_modules[email protected]@expresslibrouterindex.js:47:12)

Original address https://www.mgenware.com/blog/?p=2924&utm_source=tuicool&utm_medium=referral

Test environment for this article: Node.js 4.2.2, node-mysql 2.9.0

encountered with node-mysqlCannot enqueue Handshake after already enqueuing a Hand shake. This error message means that a certain database connection has been executed and multiple connections cannot be made. Encountered such a situation, first look at whether the code has multiple calls to the same database connectionconnectMethod, after this obvious error is eliminated, see if it is callingconnectAn implicit connection operation occurred before, such as calling directly when not connectedqueryIndirectconnect, The following code,createConnectionCall directly afterqueryWill also trigger the connection:

var mysql = require('mysql');
mysql.createConnection({...}).query('...', (err, res) => {
    if (err) {
        // handle errors
    }
    // Implicit connection, if there is no connection error, the data will return normally
});

Of course, you can also directly remove the explicitconnectCall, let it goqueryTo do the implicit connection, the above error will not occur, but if this is the case, it is strongly recommended to use Pool, so that the database connection can be reused and managed as much as possible, andcreateConnectionLike the returned connection, Pool can passgetConnectionReturn a connection, you can also use it directlyqueryTo automatically reuse or create a connection. But if you usepool.getConnectionIf you are done, remember to callconnection.releaseReturn the connection to the Pool. These two methods are equivalent in most cases, unless the query contains multiple statements, you can refer to this link:Difference between using getConnection() and using pool directly in node.js with node-mysql module?.

TL;DR You need to establish a new connection by calling the createConnection method after every disconnection.

I was using the popular Mysql module for Node.js which is node-mysql and everytime, after the first page load was encountering a weird error with full stack trace.

What’s the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

Error: Cannot enqueue Handshake after invoking quit.
    at Protocol._validateEnqueue ......
    ...
    ...

Basically, the problem is that, if you’ve terminated an existing connection object then that cannot be re-connected afterwards.

So the solution is to call the createConnection method (followed by connect()) to create a new connection whenever you have terminated the old/existing connection.

If you’re using the node-postgres module for postgresql support in Node, then you’ll have to do something similar, i.e., call the connect method with the connection string to create new connections if you terminate the old connection (during the previous process/request) by calling pg.end() or client.end().

Note: If you’re serving web requests, then you shouldn’t be ending connections on every request. Just create a connection on server startup and use the connection/client object to query all the time. You can listen on the error event to handle server disconnection and for reconnecting purposes. Full code here.

You can do something similar with the postgres module’s clients if you’re creating them manually using pg.Client. Although when using the built-in pool approach to serve web requests, call pg.connect() on every request and you should be fine. Just make sure you’ve attached an event handler on the error event to prevent Node from crashing if the postgres server stops/restarts for some reason.

Calling pg.connect() will retrieve an existing pooled client or create a new one ONLY if all the pooled clients are busy and the pool is NOT full.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Hello guys, back with me. In the nigh i will share about how to fix error in nodejs + mysql. This is a error message «Cannot enqueue Handshake after already enqueuing a Handshake».

Why i get this error ? it is a bug in mysql module, you dont need to connect if you already create createConnection. so you must delete your connection and delete end connection.

below is the example code.

Before


var con = require('../databases/db');

/* GET users listing. */
router.get('/', function(req, res, next) {
 con.connect(function(err) {
   if (err) throw err;
   con.query("SELECT * FROM Kriteria", function (err, result, fields) {
     if (err) throw err;
     res.render('kriteria/index',{
      kriterias:result
     });
   });
 });
});

After delet connection


var con = require('../databases/db');

/* GET users listing. */
router.get('/', function(req, res, next) {
   con.query("SELECT * FROM Kriteria", function (err, result, fields) {
     if (err) throw err;
     res.render('kriteria/index',{
      kriterias:result
     });
   });
});

Now, you solve your problem.

Понравилась статья? Поделить с друзьями:
  • Error cannot delete branch master checked out at
  • Error cannot delete branch main checked out at
  • Error cannot delete branch git
  • Error cannot declare member function to have static linkage
  • Error cannot create video capture filter микроскоп