Node.js - Server Closed The Connection?
I'm running a web app on a Node.js server and I need it to be online all the time, so I'm using forever. But here is what I'm getting after a period of time: Error: Connection lost
Solution 1:
The error isn't related to your HTTPS instance, it's related to your MySQL connection.
The connection to the database is ending unexpectedly and isn't being handled. To fix this, you can use a manual reconnect solution, or you can use connection pooling which automatically handles reconnects.
Here is the manual reconnect example taken from node-mysql's documentation.
var db_config = {
host: 'localhost',
user: 'root',
password: '',
database: 'example'
};
var connection;
functionhandleDisconnect() {
connection = mysql.createConnection(db_config); // Recreate the connection, since// the old one cannot be reused.
connection.connect(function(err) { // The server is either downif(err) { // or restarting (takes a while sometimes).console.log('error when connecting to db:', err);
setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
} // to avoid a hot loop, and to allow our node script to
}); // process asynchronous requests in the meantime.// If you're also serving http, display a 503 error.
connection.on('error', function(err) {
console.log('db error', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usuallyhandleDisconnect(); // lost due to either server restart, or a
} else { // connnection idle timeout (the wait_timeoutthrow err; // server variable configures this)
}
});
}
handleDisconnect();
Post a Comment for "Node.js - Server Closed The Connection?"