'MySQL node.js PROTOCOL_CONNECTION_LOST error
I've been encountering this problem where the mysql connection times out every 2 minutes or so. here's my code.
require('dotenv').config();
const LocalStrategy = require('passport-local').Strategy;
const mysql = require('mysql');
const bcrypt = require('bcrypt');
const db = require('../models/database');
handleDisconnect = () => {
const connection = mysql.createConnection(db.connection);
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;
}
});
return connection;
}
connection = handleDisconnect();
connection.query('USE ' + db.database);
handleDisconnect();
//connection.end()
}
If I include connection.end() it breaks it.
I tried this handleDisconnect(); workaround but it doesn't work either.
Any help is appreciated.
Solution 1:[1]
require('dotenv').config();
const LocalStrategy = require('passport-local').Strategy;
const mysql = require('mysql');
const bcrypt = require('bcrypt');
const db = require('../models/database');
// this method keeps the server connected to db
mysql.createConnection({
host: "hostname", // localhost or remote hostname
username: "your_username",
password: "your_password",
port: "port_number_used_for_db"
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jkalandarov |
