Node.js Mysql Connection Terminated - javascript

I'm trying to insert a basic form into my database to learn how node works, but I keep getting a fun little error returned..
error when connecting to db: { [Error: Connection lost: The server closed the connection.] fatal: true, code: 'PROTOCOL_CONNECTION_LOST' }
I have a wrapper for disconnection, but that doesn't seem to help either.
SELECT * FROM player returns nothing in mysql as well, so nothing is being inserted.
Here is my server.js file: (I omitted connection credentials of course)
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();
app.use(express.static(__dirname));
app.use(express.json());
app.use(express.urlencoded());
app.post("/post",function(req,res) {
console.log(JSON.stringify(req.body));
res.send("Username is: "+req.body.user+".");
var post = {
name:req.body.user,
password:"testing",
email:"fake#email.com"
};
connection.query("INSERT INTO player VALUES ?",post,function(err,result) {
console.log(err);
console.log(result);
});
});
app.listen(80, function() {
console.log("Server running on port 80");
});
Why is my connection being severed?

Add
con.connect();
before app.listen(80... should fix the problem.

Related

How to prevent restart my node server after an error has occurred?

Connection.js
const mysql = require("mysql");
var mysqlConnection = mysql.createConnection({
host: "xxx.amazonaws.com",
user: "admin",
password: "xxx",
database: "xxx",
multipleStatements: true,
});
var connect= ()=> { return new Promise((resolve,reject)=>{
mysqlConnection.connect((err) => {
if (err) {
reject(err)
}
else{
resolve ("Success")
}
});
})
}
module.exports = { mysqlConnection,connect};
Server.js
app.get("/", (req, res) => {
var fetchDetail = `xxxx`
connect()
.then((result)=>{
console.log(result)
mysqlConnection.query(fetchDetail, (error, result, fields) => {
if (error) {
console.log(error);
}
else {
console.log("Successfull");
res.send(result);
}
});
})
.catch((err)=>{
let e=new Error("Something went wrong")
next(e)
})
}
);
app.use(function (err, req, res, next) {
console.log(err)
res.status(500).send('Something broke!')
})
If I hit ("/") when my internet is closed I get an error as a response because server is unable to connect with Aws MySQL instance. But after I restart my internet and hit ("/") I am still getting an error response until I restart my node server again.
Goal: I do not want to restart my server after any error.
You dont need to restart all server.
You need to look for fatal flag on err in your .catch((err)=>{
and try to reconnect to mysql then you catch fatal: error (like disconnect) by calling mysql.createConnection({ ... params ... }); again

Connexion lost after exactly 1 minut / 60 seconds of execution

I have a web server run by node.js
It uses Express, Socket.io, and MySQL
I use socket.io to transmit data from client to server, and also to call queries.
After implementing SQL connexion and queries, the server started to stop after exactly 60 seconds running it.
SQL part in the index.js file:
// SQL
var mysql = require('mysql');
var con = mysql.createConnection({
host: "...",
user: "...",
password: "...",
database: "..."
});
//Socket.io
var io = require('socket.io') (serv, {});
io.sockets.on('connection', function(socket) {
// Select
socket.on("recherche", function(data) {
if (err) throw err;
con.query("SELECT * FROM ..", function (err, result, fields) {
if (err) throw err;
socket.emit("...", {data: result});
});
});
// Insert into
socket.on("...", function(data) {
con.connect(function(err) {
if (err) throw err;
var sql = "INSERT INTO ... VALUES (...)";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
});
});
Everything is working just fine for 60 second after start the server.
Then, I have this error message in the nodejs console:
C:\Users\...>node index.js
events.js:187
throw er; // Unhandled 'error' event
^
...
Error: Connection lost: The server closed the connection.
...
fatal: true,
code: 'PROTOCOL_CONNECTION_LOST'
Thank you in advance to read my question :D
connection = mysql.createConnection(db_config); // Recreate the connection, since
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') { // Connection to the MySQL server is usually
handleDisconnect();
} else {
throw err;
}
});

How to get result from function in other file in node.js

Trying to call database query from other javascript file in NodeJS.
Sample database file:
function addUser(user) {
connection.connect(function (err) {
if (err) {
console.error('Error connecting: ' + err);
}
console.log('Connected as id ' + connection.threadId);
});
var sql = "INSERT INTO `mobile`.`main` (`userId`) VALUES (?);"
var inserts = [user];
connection.query(sql, inserts, function (error, results) {
console.log('query');
if (error) {
return error;
} else {
console.log('Success Query');
return results;
}
});
connection.end(function (err) {
if (err) {
console.error('Error connecting: ' + err);
}
console.log('Connection closed!');
});
}
module.exports = addUser;
Sample main.js file:
app.get('/api/mysql/:user', function (req, res) {
var user = req.params.user;
addUsers(user)
res.json({
SQLResp: 'Query succes',
result: addUsers.result
});
});
How to get the result from the first file and use it as a response in the main js?
Welcome to stack overflow.
this is missing from your database file, How did you got connection there?
Here's a sample example over How to export database connection and use this to make calls from other files.
Also do read about callbacks-functions, Promises, async-await and Asynchronous functions of JavaScript. These are basics of JavaScript and also do go through NodeJS docs.
DB.js:
const MYSQL = require('mysql');
const connection = MYSQL.createConnection({
host: 'localhost', // url of db
user: 'root',
password: 'root',
database: 'dbName'
});
module.exports = connection;
Now will use this connection from other file to call database.
app.js:
const db = require('./DB'); // Path of your db connection file. I named it DB.js on same level as of app.js
function addUser(user) {
// Since database calls are async in NodeJS thus using promises.
return new Promise ( (resolve, reject) => {
db.connect(function (err) {
if (err) {
console.error('Error connecting: ' + err);
return reject(err);
}
console.log('Connected as id ' + connection.threadId);
});
var sql = "INSERT INTO `mobile`.`main` (`userId`) VALUES (?);"
var inserts = [user];
db.query(sql, inserts, function (error, results) {
console.log('query');
if (error) {
return reject(err);
} else {
console.log('Success Query');
return resolve(results);
}
});
db.end(function (err) {
if (err) {
console.error('Error connecting: ' + err);
}
console.log('Connection closed!');
});
});
}
app.get('/api/mysql/:user', function (req, res) {
var user = req.params.user;
addUsers(user)
.then (result => { // When addUsers will resolve promise will be in then.
res.json({
SQLResp: 'Query succes',
result: result
});
})
.catch(err => { // If promise is rejected then on catch
res.json({
SQLResp: 'Query err',
result: err
});
});
});
You need to pass a callback into your addUser function, and call it inside your connection.query with the results.
Currently, when you return, you're returning inside another callback, which means the data is more or less being thrown away.
That will also let you handle all of the error cases in a way you can tell the user about.

MongoDB output to browser

Hello I'm learning mongoDB and trying to print out my database query results to the browser.
I have a program working where it writes the output JSON to the console using console.log()
Is there a way to use res.send() (using express) or response.write() and response.send() to simply output the raw JSON data that the database query gets?
In other words, How can I make my database invokatation return a string?
// Use connect method to connect to the server
var invokeDatabase = function() {
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to database server");
findDocuments(db, function() {
findDocumentsFiltered(db, function() {
db.close();
});
});
});
};
//routes
app.get('/', function(req, res) {
console.log("Someone connected.")
res.send("accessing database... " + invokeDatabase())
//res.send('Welcome G')
})
This example may help you to understand
// Use connect method to connect to the server
var invokeDatabase = function(callback) {
MongoClient.connect(url, function(err, db) {
//assert.equal(null, err);
if(err) {
console.log("Unable to connect database");
callback(err, null);
return;
}
console.log("Connected successfully to database server");
findDocuments(db, function() {
findDocumentsFiltered(db, function(err, data) {
callback(err, data);
db.close();
});
});
});
};
//Added for demo. Here users is collection
var findDocumentsFiltered = function(db, callback) {
db.collection('users').find({}).toArray(function(err, userList) {
callback(err, userList);
});
};
//routes
app.get('/', function(req, res) {
console.log("Someone connected.")
invokeDatabase(function(err, data) {
if(err)
res.status(500).json({error: err});
else
res.json(data);
}))
//res.send('Welcome G')
})

How can i pipe mysql data to a browser window instead of the console in Nodejs?

Hi I am currently trying to output mysql data to a browser window instead of the console, and I have not a clue on how to do this in Node, which I am quite new to.
Here is the mysql.js file:
'
var mysql = require ("mysql");
var connection = mysql.createConnection({
host:"localhost",
user: "root",
});
connection.connect(function (err) {console.log( "Successfully Connected.");
if (err) throw err;
});
var query = connection.query("SELECT * FROM myTable", function (err, result, fields){
if (err) throw err;
console.log('result:', result);
});
connection.end();'
You need to create a server which you can connect to and receive data from with a browser. The most convenient and by far the simplest way to do this is HTTP. You can read about HTTP servers in node.js here. The fist code snippet on that page demonstrates a HTTP server with one handler function, which is all you need to achieve your goal.
An (untested) example for convenience:
// Dependencies
var mysql = require("mysql"),
http = require("http");
// This holds our query results
var results;
// Connect to database
var connection = mysql.createConnection({
host: "localhost",
user: "root"
});
connection.connect(function(err) {
if (err) throw err;
console.log("Connected to database");
});
connection.query("SELECT * FROM myTable", function(err, rows, fields) {
if (err) throw err;
results = rows;
connection.end(); // Disconnect from database
});
// Function to handle browser's requests
function requestHandler(req, res) {
res.end(JSON.stringify(results)); // Respond to request with a string
}
// Create a server
var server = http.createServer(requestHandler);
// That magic number 8080 over here is the port our server listens to.
// You can access this webpage by visiting address http://localhost:8080
server.listen(8080, function() {
console.log("Server online");
});

Categories

Resources