Node.js MySQL: Resolving "Connection lost: The server closed the connection" Error
When establishing connections to MySQL databases using Node.js, it's possible to encounter an error stating "Connection lost: The server closed the connection." This error typically occurs during periods like 12:00 to 2:00, when the TCP connection is interrupted by the server.
Solution 1: Automatic Reconnection Handling
To handle this error automatically, implement the following code:
var db_config = { host: 'localhost', user: 'root', password: '', database: 'example' }; var connection; function handleDisconnect() { connection = mysql.createConnection(db_config); connection.connect(function(err) { if(err) { console.log('error when connecting to db:', err); setTimeout(handleDisconnect, 2000); } }); connection.on('error', function(err) { console.log('db error', err); if(err.code === 'PROTOCOL_CONNECTION_LOST') { handleDisconnect(); } else { throw err; } }); } handleDisconnect();
In this code, a connection is established with the MySQL server. If the connection is lost due to a server restart or an idle timeout, the handleDisconnect() function is called, which re-establishes the connection.
Solution 2: Manual Reconnection
In the provided code, you have implemented part of the automatic reconnection mechanism, but there's a missing portion after the line connection = mysql.createConnection(kf_config);. The following code completes the implementation:
connection.connect(function(err) { if (err) { console.log("Error connecting to KFC: " + err); } else { console.log("KF connected!"); } });
You should also register an error listener on the connection object to automatically handle connection lost events. For example:
connection.on('error', function(err) { if (err.code === 'PROTOCOL_CONNECTION_LOST') { console.log("KF connection lost. Reconnecting..."); handleKFDisconnect(); } else { throw err; } });
By following these steps, you can ensure that your Node.js MySQL application handles connection loss gracefully and automatically reestablishes the connection.
The above is the detailed content of How to Resolve Node.js MySQL 'Connection lost: The server closed the connection' Errors?. For more information, please follow other related articles on the PHP Chinese website!