nodejs with mysql , cant get data from db - javascript

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.

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;

Connect to mysql on correct port JS

hey using a javascript app im making as a backend server for my website i keep getting this as an error when trying to connect to my mysql server.
ConnectionError: Failed to connect to win2k16-mcdmz:1433 - Could not connect (sequence)
and this is my script to connect to the server. is there any ideas on why it is set to 1433?
private initializeServer() {
const config = {
user: 'MCAdmin',
password: '*******',
server: 'win2k16-mcdmz',
port: 3306,
database: 'ValorantLFG',
encrypt: true
};
mysql.connect(config, (err) => {
if (err) { console.log(err); }
this.init.lfgRequestsTimeout();
//this.init.noticesTimeout();
});
}

code: "PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR" in nodeJs MySQL

I have this issue since I uploaded my code on hosting panel, my Database is different server and API is a different server
The error is code: "PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR", fatal: false}
it is working for some time but after calling another API then an error is occurring.
Here is my code
app.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'xx.xx.xx.xx',
user : 'abc',
password : '123',
database : 'XYZ',
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
Here is the controller user.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'xx.xx.xx.xx',
user : 'abc',
password : '123',
database : 'XYZ',
})
This is one code snippet of my API.
exports.getLandLord =(req, res, next)=>{
var sql =`SELECT *FROM registrations`;
connection.query(sql, function(error, result, field){
if(error){
return res.status(201).json({message:error, status:402, success:false})
}
else
if(result.length>0){
res.status(200).json({message:"Land Loard List", status:200, success:true,
users:result,})
}
else
res.status(200).json({message:"No Record Found ", status:402, success:false, users:result})
})
}
I tried googling but I was not able to make it fix.
Please can anyone help me with this issue
Your response and help would be highly appreciated
Thanks in advance.
After struggling for a long time I work around this and got code to work
refer NodeJS MySQL - How to know connection is release or not

Issue connecting to my sql database using a REST api server with Node.js

I'm very new to coding servers and javascript in general but I'm currently trying to set up a REST api server and connect it to my sql database, for the moment I am doing everything locally. I am running ubuntu 18.04 while using NODE js. I have been able to successfully create a REST api and connect to it through an url of a webpage or with Postman. I have created a sql server database through my cmd terminal and have created test data on it. I've been looking at guides to connect the REST api to the database but I think the info I'm giving the api to connect is where my issue is occurring. I am starting with this below as my server.js where i have a folder Controller and a ProductController.js file where I'm handling the route /api/products .
var http = require('http');
var express = require('express');
var app = express();
var port = process.env.port || 3000;
var productController = require('./Controller/ProductController')();
app.use("/api/products", productController);
app.listen(port, function(){
var datetime = new Date();
var message = "Server running on Port:- " + port + " Started at :- " +
datetime;
console.log(message);
});
Below is my ProductController.js file. The issue might be here but I believe it is my next file called connect.js the table in my sql database is called 'data' hence the "SELECT * FROM data" part. when I try to GET this data in postman it displays the error i set up "Error while inserting data". so I believe when running I'm not getting data from sql so conn.close() is not being reached.
var express = require('express');
var router = express.Router();
var sql = require("mssql");
var conn = require("../connection/connect")();
var routes = function()
{
router.route('/')
.get(function(req, res)
{
conn.connect().then(function()
{
var sqlQuery = "SELECT * FROM data";
var req = new sql.Request(conn);
req.query(sqlQuery).then(function (recordset)
{
res.json(recordset.recordset);
conn.close();
})
.catch(function (err) {
conn.close();
res.status(400).send("Error while inserting data");
});
})
.catch(function (err) {
conn.close();
res.status(400).send("Error while inserting data");
});
});
return router;
};
module.exports = routes;
This is my connect.js file below. I have a password for root which is not *** but is correct on my machine. I have changed root's plug in to mysql_native_password in the mysql terminal. I think the server: part is wrong, I've tried commenting it out but still no connection. I do not have SQL Server Management Studio and have not found a way to get my sql server's name through the terminal. I've seen examples that seem to range of what info you need to give the api to connect. If someone has insight on that too that would be appreciated as well. My end goal is to eventually create GET and POST routes for the database and a function to manipulate the POST data but for now I'm just trying to get things connected so I can play around with the data being GET'ed. Thanks for any insight you can give, it is much appreciated.
var sql = require("mssql");
var connect = function()
{
var conn = new sql.ConnectionPool({
host: 'localhost'
user: 'root',
password: '********',
server: 'mysql',
database: 'test'
});
return conn;
};
Looks like you may have some errors in your connect.js file:
var conn = new sql.ConnectionPool({
host: 'localhost'
user: 'root',
password: '********',
server: 'mysql',
database: 'test'
});
should be in the format of:
const pool = new sql.ConnectionPool({
user: '...',
password: '...',
server: 'localhost',
database: '...'
})
Note that you currently have both host and server, looks like only server is needed. Also, server: 'mysql' doesn't make sense if you are connecting to a MSSQL database.
Source: node-mssql documentation
To diagnose the errors you should add some logging to your catch blocks:
.catch(function (err) {
console.log('connection error', err); //or Bunyan, Winston, Morgan, etc. logging library
conn.close();
let message = "Error while inserting data"
if (process.env.NODE_ENV === 'development') { //conditionally add error to result message
message += "\n"+err.toString());
}
res.status(500).send(message); //use 5xx for server problems, 4xx for things a user could potentially fix
});
And set NODE_ENV in your environment, for example in package.json:
"scripts": {
"start": "NODE_ENV=production node app.js"
"start-dev": "NODE_ENV=development node app.js"
}

Socket.io mysql connection error

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 ?

Categories