i have developed a chat application using node js and socket io. However it is working fine for 5 to 10 minutes. But after that i keep on getting error as
db error { [Error: Connection lost: The server closed the connection.] fatal: true, code: 'PROTOCOL_CONNECTION_LOST' }
I am using below given code for reconnection but it still gives me same error.
var app = require('express')();
app.set('port', process.env.PORT || 3000);
var server = require('http').Server(app);
var io = require('socket.io')(server);
var port = app.get('port');
var mysql = require('mysql');
var db_config = {
host : 'localhost',
user : 'root',
password : '',
database : 'chatapp'
};
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();
Related
var app = require('express')();
app.get('/', (req, res) => {
var sql = require("mssql");
// config for your database
var config = {
user: 'sa',
password: 'xxxxx',
server: 'xx',
database: 'formdangky',
port :'1443'
};
(async function () {
try {
let pool = sql.connect(config)
let result1 = await pool.request()
.query('select * from dondangky')
// console.dir(result1)
// send records as a response
res.send(result1);
} catch (err) {
res.send(err)
}
})();
sql.on('error', err => {
// error handler
console.log(err);
});
});
//start listening
var port = 3000;
app.listen(port, function () {
console.log('Application started on ' + new Date());
console.log("Listening on " + port);
});
When i trying code but then the result is empty end not show something
Node JS to SQL SERVER get null empty when i trying conect with mssql from Npm https://www.npmjs.com/package/mssql#asyncawait
to get reslut from database
I am learning node.js on my own and I do not understand why I get that error "[nodemon] app crashed - waiting for file changes before starting..". I have the same code as the one on the tutorial. What can be wrong?
Thank you for your help!
const express = require('express');
const mysql = require('mysql');
//create connection
const db = mysql.createConnection({
host: 'localhost',
user : 'root',
password : '123456',
});
//connect
db.connect((err)=>{
if(err){
throw err;
}
console.log("mysql is CONNECTED");
});
const app = express();
app.get('/createdb',(req,res) =>{
let sql = 'CREATE DATABASE nodemysql';
db.query(sql,(err, result)=>{
if(err) throw err;
console.log(result);
res.send('database created');
})
})
app.get('/createdb',()=>{
console.log("server started on port 3000");
})
app.listen('3000',()=>{
console.log("server started on port 3000");
});
Make sure mysql is installed:
npm install mysql --save
Try console.error(err) followed by return:
var mysql = require("mysql");
var connection = mysql.createConnection({
host: "example.org",
user: "bob",
password: "secret"
});
connection.connect(function(err) {
if (err) {
console.error("error connecting: " + err.stack);
return;
}
console.log("connected as id " + connection.threadId);
});
Hi I am creating node js restful api by using sqlserver database , i prepare get api when i am using that api output is shown in json format, while refreshing that browser gain its shows "Error: Global connection already exists. Call sql.close() first."error . I am adding code
var express = require("express");
var sql = require("mssql");
var app = express();
//Initiallising connection string
var dbConfig = {
user: 'sa',
password: 'India123',
server: 'localhost',
database: 'sample'
};
app.get('/login', function (req, res) {
// connect to your database
var data = {
"user": ""
};
sql.connect(dbConfig, function (err) {
if (err) console.log(err);
var request = new sql.Request();
request.query('select * from Login', function (err, result) {
if (err) console.log(err)
// send data as a response
//res.send(result.recordset);
data["user"] = result.recordset;
res.send(data);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
Please correct me code . thanks advance
// db.js
var mssql = require("mssql");
var dbConfig = {
user: 'sa',
password: 'India123',
server: 'localhost',
database: 'sample'
};
var connection = mssql.connect(dbConfig, function (err) {
if (err)
throw err;
});
module.exports = connection;
// app.js
var db = require("db");
var express = require("express");
var app = express();
app.get('/login', function (req, res, next) {
var request = new db.Request();
request.query('select * from Login', function (err, result) {
if (err)
return next(err);
var data = {};
data["user"] = result.recordset;
res.send(data);
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
Don't use sql.Connection() any more, instead use sql.ConnectionPool()
Connections
Internally, each ConnectionPool instance is a separate pool of TDS connections. Once you create a new Request/Transaction/Prepared Statement, a new TDS connection is acquired from the pool and reserved for desired action. Once the action is complete, connection is released back to the pool. Connection health check is built-in so once the dead connection is discovered, it is immediately replaced with a new one.
IMPORTANT: Always attach an error listener to created connection. Whenever something goes wrong with the connection it will emit an error and if there is no listener it will crash your application with an uncaught error.
Create pool and use connection.
const pool = new sql.ConnectionPool({ /* config */ })
Entire Article how to use pool and close pool.
https://www.npmjs.com/package/mssql
var sql = require("mssql");
const pool = new sql.ConnectionPool({
user: 'sa',
password: 'Pass#123',
server: 'SAI-PC',
database: 'Demo'
})
var conn = pool;
conn.connect().then(function () {
var req = new sql.Request(conn);
req.query("SELECT * FROM Product").then(function (recordset) {
console.log(recordset);
conn.close();
})
.catch(function (err) {
console.log(err);
conn.close();
});
})
.catch(function (err) {
console.log(err);
});
I'm running a daemon with a mongo connection pool. It runs fine for days but eventually it crashes and every subsequent request gets this error:
MongoError: server instance pool was destroyed
The code is similar to this:
var MongoClient = require('mongodb').MongoClient;
var express = require('express');
var app = express();
MongoClient.connect(config.mongo.url, function(err, db) {
app.use('/', function(req, res, next) {
db.collection('somecollection').find({}).toArray(function(err, result) {
console.log(result);
});
})
var server = require('http').Server(app);
server.listen(config.worker.port, function() {
var address = server.address();
logger.info({
address: address.address,
port: address.port
}, 'New Worker created');
});
});
Restarting the process fixes the issue, but I would like the application to somehow elegantly reconnect and reset the "db" object there.
This is what we are using - if connection fails, it tries to reconnect after 5 seconds. It is written for mongoose, but we are just re-running connection when detecting error, which should be done for any framework.
// Connect to mongodb
const connect = function () {
const options = {server: {socketOptions: {keepAlive: 1}}};
mongoose.connect(config.db, options);
};
connect();
mongoose.connection.on('error', err => {
let stack;
if (err) {
stack = err.stack;
}
winston.error('Mongo crashed with error', {err, stack});
}); // eslint-disable-line no-console
mongoose.connection.on('disconnected', () => {
setTimeout(connect, 5000);
});
I am trying to connect to the mongodb database on mongolabs(mlabs). I connect successfully when I run the code on my local computer and server.But When I run on my aws server I get this error database error { [MongoError: socket hang up] name: 'MongoError', message: 'socket hang up' }
Code trial.js:
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var mongojs = require('mongojs');
var db = mongojs('mongodb://user:pass#ds01312192.mlab.com:133492/database', ['mohd'], { ssl : true });
db.on('error', function (err) {
console.log('database error', err);
});
db.on('connect', function () {
console.log('database connected');
});
db.mohd.find({}, function (err, docs) {
if(err){
console.log("error");
}else{
console.log(docs+"found");
}
});
app.set('view engine','ejs');
app.get('/',function(req,res){
console.log("hi");
});
app.listen(9000,function(){
console.log("server strated");
});
// catch 404 and forward to error handler
module.exports = app;
Got connection error on Amazon Web Service server but successful on local computer.
Ok so I solved the issue it was due to ssl connect method just removed it and was solved.
Use Instead:
var db = mongojs('mongodb://user:pass#ds01312192.mlab.com:133492/database', ['mohd']);