Socket.io mysql connection error - javascript

When i started my socket on the npm , my Mysql conection going to down about 30 sec .I do not know why. The mysql insert method worked . But when i am waiting about 1 min -30 sec the conenction shut down.
This is error code ;
events.js:141
throw er; // Unhandled 'error' event
^
Error: Connection lost: The server closed the connection.
at Protocol.end (C:\xampp\htdocs\tem\node_modules\mysql\lib\protocol\Protocol.js:109:13)
at Socket. (C:\xampp\htdocs\tem\node_modules\mysql\lib\Connection.js:115:28)
at emitNone (events.js:72:20)
at Socket.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:921:12)
at nextTickCallbackWith2Args (node.js:442:9)
at process._tickCallback (node.js:356:17)
This is my source code;
var app = require('express')();
var mysql = require("mysql");
var http=require('http').Server(app);
var io=require('socket.io')(http);
var con = mysql.createConnection({
host: "hostname",
user: "username",
password: "pw",
database: "db"
});
con.connect(function(err){
if(err){
console.log('UnSuccesfull');
return;
}
console.log('Succesfull');
});
app.get("/",function(req,res){
res.sendfile(__dirname+"/asd.html");
});
io.on('connection',function(socket){
var UserLog={
Log:'A User Connected'
};
con.query('Insert Into Log SET ?',UserLog ,function(err){
if(err)
console.log(err);
});
});
var port=xx;
http.listen(port,'xx.xx.xx');

I recommend to you, use connection pooling.
You can create connection pool like that;
var pool = mysql.createPool({
connectionLimit : 60,
host : hostname,
user : dbUser,
password: dbPass,
database: dbName,
multipleStatements: true
});
And when you need to run query on mysql;
pool.getConnection(function(err, connection) {
connection.query( "SELECT * FROM `users`", function(err, users) {
connection.release();
});
});

io.on('connect')*
The database rules is correct ?

Related

Node.js MySQL Connection Error. ECONNREFUSED

I have 2 servers, one running the frontend code (Node.js, express) and the other running MySQL with PHPMyAdmin, both are working standalone and I can confirm the MySQL database is running on 3306 but whenever I try to connect via Node.js (code below) I get a connection refused error.
const conn = mysql.createConnection({
host: '192.168.1.250',
user: 'mcd',
password: '**********',
database: 'mcd'
})
conn.connect(function(err) {
if (err) throw err;
})
The IP address I have used for the host is the IP address of the MySQL server. So unsure why it cannot connect since it is running on the default port.
Here is my connection to Node.js:
pool = mysql.createPool({host:"localhost"
,port:"3306"
,database:"db_name"
,user:"user_name"
,password:"password_for_user"
,timezone:"utc"
,multipleStatements:true
,max:1000
,min:1
,idleTimeoutMillis:defs.QUERY_TIMEOUT});
if ( pool && pool.getConnection ) {
pool.getConnection(function(errsts, conn) {
var resp = {};
if ( errsts ) {
resp['error'] = errsts;
return;
}
resp['state'] = "connected";
if ( cbRoutine ) {
cbRoutine(conn, resp, objParams);
if ( conn != undefined ) {
conn.release();
}
}
});
}
localhost is correct for my usage, you should replace its your name or IP address.
defs.QUERY_TIMEOUT is defined in my source as:
var QUERY_TIMEOUT = 10 * 1000;
In my code cbRoutine is a call back function passed in as a parameter to call on successful connection.
The ECONNREFUSED error indicates that it can't connect to where the function is hosted (in this case localhost)
dbConnection.js
const mysql = require('mysql');
const connection = mysql.createPool({
connectionLimit: 10, // default = 10
host: '127.0.0.1',
user: 'root',
password: '',
database: 'dname'
});
module.exports = connection;

Unable to connect to MSSQL server through Node, while Intellij connection works (MacOS)

I'm running into a strange behaviour where I'm unable to connect to an instance of MSSQL server running locally on docker when using a Node js script, but I can connect to it using Intellij's built-in JDBC connector.
This is the script:
import mysql from "mysql"
const connection = mysql.createConnection({
host : 'localhost',
user : 'sa',
password : 'P#55w0rd!',
database : 'ml_project',
port: 1433,
connectionLimit: 15,
queueLimit: 30,
acquireTimeout: 1000000
});
connection.connect(function(err) {
if ( !err ) {
console.log("Connected to MySQL");
} else if ( err ) {
console.log(err);
}
});
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log(results[0].solution);
connection.end();
});
Which outputs the following error:
Error: Connection lost: The server closed the connection.
at Protocol.end (/Users/IoannouK/ml_project/node_modules/mysql/lib/protocol/Protocol.js:112:13)
at Socket.<anonymous> (/Users/IoannouK/ml_project/node_modules/mysql/lib/Connection.js:94:28)
at Socket.<anonymous> (/Users/IoannouK/ml_project/node_modules/mysql/lib/Connection.js:526:10)
at Socket.emit (events.js:322:22)
at endReadableNT (_stream_readable.js:1187:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
--------------------
at Protocol._enqueue (/Users/IoannouK/ml_project/node_modules/mysql/lib/protocol/Protocol.js:144:48)
at Protocol.handshake (/Users/IoannouK/ml_project/node_modules/mysql/lib/protocol/Protocol.js:51:23)
at Connection.connect (/Users/IoannouK/ml_project/node_modules/mysql/lib/Connection.js:116:18)
at Object.<anonymous> (/Users/IoannouK/ml_project/dist/mysql.js:17:12)
at Module._compile (internal/modules/cjs/loader.js:1156:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1176:10)
at Module.load (internal/modules/cjs/loader.js:1000:32)
at Function.Module._load (internal/modules/cjs/loader.js:899:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47 {
fatal: true,
code: 'PROTOCOL_CONNECTION_LOST'
}
/Users/IoannouK/ml_project/dist/mysql.js:27
throw error;
^
And this is the settings panel in my Intellij which works:
I have also tried connecting to a remote database, as well as using a python script, but I received the same results.
const express = require("express");
var sql = require("mssql");
const multer = require("multer");
var config = {
user: "jsudjac",
password: "$#jsuapple",
server: "10.1.4.125",
database: "JSULLC_Test",
};
var dataSource = {
user: "********",
password: "*******",
server: "10.2.2.2",
database: "Stock_Test",
};
const dbconn1 = sql.connect(config, (err) => {
if (!err) {
console.log("Connected to the database");
} else {
console.log("Problem in connecting to database");
console.log(err);
console.log("testing");
}
});

node-postgres: [error] This socket has been ended by the other party

I use node-protgres to manipulate the db in my nodejs app.
What I have done:
const { Pool, Client } = require('pg')
var dbconnect = {
user: 'xxxxx',
database: 'xxxxx',
password: 'xxxxx',
host: 'xxxxx.yyyyy.zzzzz.eu-west-1.rds.amazonaws.com',
port: 0000,
max: 20, // max number of clients in the pool
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000
};
const pool = new Pool(dbconnect);
pool.on('error', function (err, client) {
console.error('idle client error', err.message, err.stack)
});
function listOfPets(req, res) {
pool.connect(function (err, client, done) {
if (err) {
return console.error('error fetching client from pool', err);
}
var sql =
"SELECT * FROM pets"
client.query(sql, function (err, result) {
done();
if (err) {
return console.error('error running query', err);
}
... //Handle the result
});
});
}
The function is working fine, however the server keep sending me the error report OK to severe. I checked the log:
idle client error This socket has been ended by the other party Error:
This socket has been ended by the other party
at Socket.writeAfterFIN [as write] (net.js:291:12)
at Connection.end (/var/app/current/node_modules/pg/lib/connection.js:313:22)
at global.Promise (/var/app/current/node_modules/pg/lib/client.js:410:23)
at Client.end (/var/app/current/node_modules/pg/lib/client.js:409:12)
at Pool._remove (/var/app/current/node_modules/pg-pool/index.js:135:12)
at Timeout.setTimeout (/var/app/current/node_modules/pg-pool/index.js:38:12)
at ontimeout (timers.js:365:14)
at tryOnTimeout (timers.js:237:5)
at Timer.listOnTimeout (timers.js:207:5)
I think the problem came from the 'done()' doesn't work or was put at wrong place.
Any suggestion is appreciated.
Try declaring the pool object inside the callback. I had a similar error with a postgres client. I solved it by declaring the client inside the callback for a GET request.
Have a look at this issue, it's where I found my solution: Github issue
Hope this can help you =). I think you can use this link to fixed http://mherman.org/blog/2015/02/12/postgresql-and-nodejs/#.WbpNjMgjGHs

nodejs with mysql , cant get data from db

can't get data from mysql db in nodejs in routes '/users'
app.get('/users', function(req,res){
connection.query("select * from users",function(err,rows){
if(!err) {
res.json(rows);
}else{
console.log(err);
res.send('err here !!' + err);
}
connection.end();
});
});
take much time and then response with
ERR_EMPTY_RESPONSE
db connection
var connection = mysql.createConnection({
host : 'localhost',
port : port,
database : 'test',
user : 'root',
password : 'root'
});
can some one help me to track this issue ,
Thanks in advance.
This issue has been resolved: I defined the MySql port as 8080 by mistake.
I corrected the port to 3306.

Node JS error "getaddrinfo ENOTFOUND"

I'm having trouble in accessing MYSQL.
There is a GET METHOD at my code below :
app.get('/users',function(request,response){
client.query('select * from User where 1=1',function(error,result){
if(error){
response.json('unfortunately fail');
console.log('unfortunately fail , error : %s',error);
console.log('error stack: %s',error.stack);
console.log('error message: %s',error.message);
throw error;
}else{
console.log('select success....');
response.json('select success....');
response.json(result);
}
});
});
When that method is executed, there is an error :
unfortunately fail , error : Error: getaddrinfo ENOTFOUND
error stack: Error: getaddrinfo ENOTFOUND
at errnoException (dns.js:37:11)
at Object.onanswer [as oncomplete] (dns.js:124:16)
at Protocol._enqueue (/node_modules/mysql/lib/protocol/Protocol.js:135:48)
at Protocol.handshake (/node_modules/mysql/lib/protocol/Protocol.js:52:41)
at Connection.connect (/node_modules/mysql/lib/Connection.js:123:18)
at Connection._implyConnect (/node_modules/mysql/lib/Connection.js:417:10)
at Connection.query (/node_modules/mysql/lib/Connection.js:199:8)
at app.listen.host (/web.js:70:10)
at callbacks (/node_modules/express/lib/router/index.js:164:37)
at param (/node_modules/express/lib/router/index.js:138:11)
at pass (/node_modules/express/lib/router/index.js:145:5)
at Router._dispatch (/node_modules/express/lib/router/index.js:173:5)
And this is about the variables (express, mysql ...)
var http = require('http');
var express = require('express');
var request = require('request');
var mysql = require('mysql');
var client = mysql.createConnection({
host:'http://nodejs.somewhere.com/WebMysql',
port : 3306,
user : 'user',
password : 'password',
database : 'database'
});
var app = express();
app.use(express.bodyParser());
app.use(app.router);
Your host setting for your mysql database connection is incorrect (ENOTFOUND for getaddrinfo means DNS resolution failed). It needs to be just the hostname of the mysql server (e.g. nodejs.somewhere.com).

Categories