Node Connection Error While contacting MySql? - mysql

I wrote a connector to get the data from the mysql and when iam running the Mysql connector inside a route it is showing error and the browser is running into a infinite loop.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
//var mongoose = require('mongoose');
//Connect to Mongoose
//mongoose.connect('mongodg://localhost/malwares');
//var db = mongoose.connection()
//Connect to Mysql
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '192.168.150.94',
user : 'root',
password : 'negalkgkgkal',
database : 'dbnamehere'
});
connection.connect();
//connection.query('SELECT * from detection', function(err, rows, fields) {
//if (!err)
//console.log('The solution is: ', rows);
//else
// console.log('Error while performing Query.');
//});
//connection.end();
//Mysql connection ends
app.get('/' , function(req ,res){
res.send('Goto /api/malware for detection results');
});
app.get('/malwares' , function(req , res){
console.log('Hello');
connection.query('SELECT * from rest', function(err, rows, fields) {
if (!err)
console.log('The solution is: ', rows);
else
console.log('Error while performing Query.');
});
});
connection.end()
app.listen(3000);
console.log('Listening on port 3000');
Error Log
Listening on port 3000
Hello
Error while performing Query.
And also the browser is not responding after this.
I even tried using node-inspector it gave me error like this protocol-enqueue-after-fatal-error-in-node-mysql
Any suggestions on how to solve this error?
P.S :: Database is there and also the table exists,for this purpose of error debugging i have queried another table which i commented in the code and it ran succesfully.
Error:
{ Error: Cannot enqueue Query after invoking quit.
at Protocol._validateEnqueue (/var/www/Rest/node_modules/mysql/lib/protocol/Protocol.js:202:16)
at Protocol._enqueue (/var/www/Rest/node_modules/mysql/lib/protocol/Protocol.js:135:13)
at Connection.query (/var/www/Rest/node_modules/mysql/lib/Connection.js:208:25)
at /var/www/Rest/app.js:39:13
at Layer.handle [as handle_request] (/var/www/Rest/node_modules/express/lib/router/layer.js:95:5)
at next (/var/www/Rest/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/var/www/Rest/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/var/www/Rest/node_modules/express/lib/router/layer.js:95:5)
at /var/www/Rest/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/var/www/Rest/node_modules/express/lib/router/index.js:335:12) code: 'PROTOCOL_ENQUEUE_AFTER_QUIT', fatal: false }

If I am not mistaken you don't need connection.connect() part if connection is defined in same file (like you have), you try commenting out that line and then run it.
I know, I encountered some problems because of that

Related

NodeJS (Express) with MySQL - How to handle connection resets?

I'm running my website with NodeJS, I'm using the Express framework.
Since MySQL is the only database type at my hosting, I went with it.
I created a db.js file:
const mysql = require('mysql');
const con = mysql.createConnection({
host: .........
user: ...........
password: ............
database: ............
});
con.connect(function(err) {
if (err) {
//throw err;
console.error(err.message);
} else {
console.log('Connected Ro MySQL!');
}
});
module.exports = con;
And I using it like:
const db = require(path.join(__dirname, 'db'));
db.query('select * from table where name = ?', request.params.id, (error, result) => {
if (error) {
response.send(error.message);
} else {
//My Render Stuffs Here
});
}
});
My website works fine however sometimes let's say once every 2 weeks there is a MySQL connection reset, I think the database not available for a minute or so for some reason, and then my website crashes, I have to manually restart NodeJS what is very annoying.
Error in the console:
node:events:355
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (node:internal/stream_base_commons:211:20)
[...]
errno: -4077,
code: 'ECONNRESET',
syscall: 'read',
fatal: true
}
How should I change my codes to prevent crashing? I replaced throw err; with the console.error(err.message); but it only works when I start the website, not when a connection reset happens at runtime.
Found the solution: Replace createConnection with createPool and totally remove con.connect since createPool doesn't need it. That's it, now it's not crashes when the db unavailable.

How to fetch data from MySQL database with Node

I'm new to react, developing a recipe-app and I got a problem while displaying the data from MySQL database. The connection was created successfully, however, I'm not sure about how to reach the data. When I run node server.js in my terminal, I get "connected", When I visit the localhost:8080/users, I get "This site can't be reached" message and in my terminal:
`events.js:187
throw er; // Unhandled 'error' event
^
Error: Cannot enqueue Handshake after already enqueuing a Handshake.`
I'm a little stuck here. Anyone knows a solution or direct me a little bit? Thank you so much!
Server.js
const express = require('express');
const app = express();
const PORT = 8080;
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'recipe_app'
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected!');
});
//creating route for the app
app.get('/users', (req, res) => {
connection.connect();
connection.query('SELECT * from users', function(err, rows, fields) {
if (!err) {
res.send(JSON.stringify(rows));
} else {
console.log('Error while performing Query.');
}
});
connection.end();
});
//making server listen to request
app.listen(PORT, () => {
console.log(`Server running at : http://localhost:${PORT}/`);
});
You're trying to reconnect to mysql after the connection has been established.
See my comments on the code below
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'recipe_app'
});
connection.connect((err) => { // This creates the connection
if (err) throw err;
console.log('Connected!');
});
And when you're trying to resolve your GET routes, you're trying to connect again
//creating route for the app
app.get('/users', (req, res) => {
connection.connect(); // reconnect here
Since you're using the default connection method, trying to connect to an already established connection will cause the driver to throw a Handshake error.
If you want to re-use the connection, store it in a variable and then re-use it in other part of your code.
If you want to manage multiple connections instead, I suggest you to look at createPool instead.
Try removing the connection.connect() and connection.end() from app.get

why do i get an error connection in nodejs - mysql (trying remote connection)

I recently started learning Nodejs to connect to MySQL and i'm having connection issues. I tried using putty to connect and i'm able to do so without any issues
this is my example.route.js file
const express = require('express'),
router = express.Router(),
mysql = require('mysql');
var connection = mysql.createConnection({
host: <ipaddress>,
port: <default Port>,
user: 'root',
password: <given password>,
database: <db name>,
connectionTimeout: 30000
});
connection.connect((error) => {
if (error) {
console.log('error connecting: ' + error);
} else {
console.log('Connected to server');
}
});
connection.query('SELECT * FROM test', function(err, results, fields) {
console.log('results in table: ' + results);
console.log('fields in table: ' + fields); // -1
connection.release();
if (err) throw error;
});
connection.end();
module.exports = router;
i get the following error => Error: connect ECONNREFUSED (Will update with complete error in a few hours)
As i mentioned before i used PUTTY in order to make sure there was an issue when connecting but i was able to connect to the given database name, host with the same user and password.
Not sure if this helps is an ubuntu server with MySQL
Anyone has an idea of why i'm getting the connection error? I would appreciate it the help

ETIMEOUT error | Google Cloud SQL database with NodeJS

I have created a mysql database on google cloud that I'd like to access from a separate node web application (also running on google cloud). I am testing the connection locally on my computer first, and when I run the following code locally I can successfully establish a connection to my database and see the data in it.
'use strict';
// [START app]
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
const mysql = require('mysql');
var connection = mysql.createConnection({
host : 'Cloud SQL IP',
user : 'username',
password : 'password',
database : 'db_name'
});
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
// Make globals.js accessible
app.use(express.static(__dirname + '/'));
app.get('/', (req, res) => {
connection.connect();
connection.query('SELECT * FROM Users', function (error, results, fields) {
if (error) throw error;
console.log(results);
});
connection.end();
res.status(200).send('Hello World!');
});
app.get('/login', (req, res) => {
res.status(200).send();
});
// [START server]
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});
// [END app]
However when run this same code in my google app engine (for both debugging on port 8080 and fully deployed on https://myapp.appspot.com) I get the following timeout error:
{ Error: connect ETIMEDOUT
at Connection._handleConnectTimeout (/home/megan_cooper2900/project/node_modules/mysql/lib/Connection.js:419:13)
at Socket.g (events.js:292:16)
at emitNone (events.js:86:13)
at Socket.emit (events.js:185:7)
at Socket._onTimeout (net.js:338:8)
at ontimeout (timers.js:386:14)
at tryOnTimeout (timers.js:250:5)
at Timer.listOnTimeout (timers.js:214:5)
--------------------
at Protocol._enqueue (/home/megan_cooper2900/project/node_modules/mysql/lib/protocol/Protocol.js:145:48)
at Protocol.handshake (/home/megan_cooper2900/project/node_modules/mysql/lib/protocol/Protocol.js:52:23)
at Connection.connect (/home/megan_cooper2900/project/node_modules/mysql/lib/Connection.js:130:18)
at app.get (/home/megan_cooper2900/journeyma/app.js:31:13)
at Layer.handle [as handle_request] (/home/megan_cooper2900/project/node_modules/express/lib/router/layer.js:95:5)
at next (/home/megan_cooper2900/project/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/megan_cooper2900/project/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/megan_cooper2900/project/node_modules/express/lib/router/layer.js:95:5)
at /home/megan_cooper2900/project/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/megan_cooper2900/project/node_modules/express/lib/router/index.js:335:12)
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true }
Why is this not working on the Google App Engine application?
In your connection configuration for mysql,host does not work on App Engine. You have to use socketPath . socketPath is the path to a unix domain socket to connect to. When used host and port are ignored. (transferred knowledge from using Loopback on App Engine flex. it had me banging my head for days lol). It's value is your Cloud SQL Instance connection name
so in your case, it should look like this: /cloudsql/my-project-12345:us-central1:mydatabase
var connection = mysql.createConnection({
socketPath : '/cloudsql/my-project-12345:us-central1:mydatabase',
user : 'username',
password : 'password',
database : 'db_name'
});
It's a similar process if you're using Postgres on GCloud which is answered here
I also did faced the same issue and I was using Kubernetes pods to access my CloudSQL instance. I got a fix by increasing the timeout in the configuration.
cloudSqlConfig: {
connectionLimit: 10,
host: 'your-host-ip',
user: process.env.DB_USERNAME,
password: process.env.DB_PASSKEY,
database: 'myDB',
connectTimeout: 20000,
waitForConnections: true,
queueLimit: 0
},

Mysql query throws ECONNREFUSED in a Node.js scheduler job

I'm trying to build a scheduler with node (v0.10.33) using the node-schedule and node-mysql modules. Code as follows:
var schedule = require('node-schedule');
var mysql = require('mysql');
var rule = new schedule.RecurrenceRule();
rule.second = 59;
schedule.scheduleJob(rule, function(){
var connection = db.connect();
console.log('Successfully established database connection.');
var resultSet = db.select(connection, 'SELECT * from notifications');
db.disconnect(connection);
});
var db = {
connect: function(){
var connection = mysql.createConnection({
host : 'localhost',
user : 'scheduler',
password : 'scheduler'
});
console.log('Trying to establish connection with database...');
connection.connect();
return connection;
},
select: function(connection, queryString){
console.log('Executing database query...');
connection.query(queryString, function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].messagetext);
return rows;
});
},
disconnect: function(connection){
connection.end();
}
}
When I execute the scheduler I get the following output:
Trying to establish connection with database...
Successfully established database connection.
Executing database query...
/home/user/notificationscheduler/scheduler.js:32
if (err) throw err;
^
Error: connect ECONNREFUSED
at errnoException (net.js:904:11)
at Object.afterConnect [as oncomplete] (net.js:895:19)
--------------------
at Protocol._enqueue (/home/user/notificationscheduler/node_modules/mysql/lib/protocol/Protocol.js:135:48)
at Protocol.handshake (/home/user/notificationscheduler/node_modules/mysql/lib/protocol/Protocol.js:52:41)
at Connection.connect (/home/user/notificationscheduler/node_modules/mysql/lib/Connection.js:119:18)
at Object.db.connect (/home/user/notificationscheduler/scheduler.js:25:14)
at Job.db.connect.mysql.createConnection.host [as job] (/home/user/notificationscheduler/scheduler.js:9:25)
at Job.invoke (/home/user/notificationscheduler/node_modules/node-schedule/lib/schedule.js:117:10)
at null._onTimeout (/home/user/notificationscheduler/node_modules/node-schedule/lib/schedule.js:369:11)
at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)
The mysql server is running locally and I tried connecting and running the same query with the scheduler user successfully.
Has anyone had any experience with these modules and what could be the cause of the problem?
Many thanks
Yes, this is because of asynchronous engine v8. When your call:
db.select(connection, 'SELECT * from notifications')
It won't wait until query is finished and result are returned. This was handling by your callback, but instead of it your are closing the connection with db and query hits an error. You need to close connection in select, if you want to correct behavior:
select: function(connection, queryString){
console.log('Executing database query...');
connection.query(queryString, function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].messagetext);
connection.end(); // Here close the connection
return rows;
});
},