Error when connecting to MYSQL Database (NodeJS, socket.io, express) - mysql

me and a friend just started to work on a little App. It uses NodeJS (with Socket.io and Express). We're kind of new into NodeJS and thus can't really comprehend why we get the error we get. Every inch of help is appreciated :)
Here's the code:
var express = require('express');
var app = express();
var serv = require('http').Server(app);
app.get('/', function(req, res) {
res.sendFile(__dirname + '/client/index.html');
});
app.use('/client', express.static(__dirname + '/client'));
serv.listen(2000);
console.log("Server started!");
var io = require('socket.io')(serv,{});
var md5 = require('md5');
var mysql = require('mysql');
var dbconn = mysql.createConnection({
host: "mySERVER",
user: "myUSER",
password: "myPASSWORD",
database: "myDBNAME"
});
dbconn.connect(function(err) {
if (err) throw err; //THE ERROR IS THROWN HERE
});
io.sockets.on("connection", function(socket) {
socket.on("register", function(obj){
var sql = 'INSERT INTO users (name, password) VALUES ("' + obj.name + '", "' + md5(obj.password) + '")';
dbconn.query(sql, function (err, result) {
if (err) throw err;
console.log("Result: " + result);
});
});
});
And here's the Error Message:
Error: connect ECONNREFUSED mySERVER:3306
at Object.exports._errnoException (util.js:1018:11)
at exports._exceptionWithHostPort (util.js:1041:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1086:14)
--------------------
at Protocol._enqueue (PROJECTPATH\node_modules\mysql\lib\protocol\Protocol.js:145:48)
at Protocol.handshake (PROJECTPATH\node_modules\mysql\lib\protocol\Protocol.js:52:23)
at Connection.connect (PROJECTPATH\node_modules\mysql\lib\Connection.js:130:18)
at Object.<anonymous> (PROJECTPATH\app.js:32:8)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
Thank you in advance!

It's a database connection error. You're mysql host and/or port are wrong.
Make sure the information passed to the mysq.createConnection function in the code below are correct:
var dbconn = mysql.createConnection({
host: "mySERVER",
user: "myUSER",
password: "myPASSWORD",
database: "myDBNAME"
});

Related

connection to a remote mysql database using node

Good mornig to you guys. I want to establish a connection to a remote mysql database using node js. but i am facing this error. I do not know if I wrongly specifies the access path to the db
code
var mysql = require('mysql');
var pool = mysql.createPool({
host: "http://kamerun-it.com/mysql",
connectionLimit : 100,
database: "****",
user: "****",
password: "*****",
multipleStatements: true
});
error
throw err;
^
Error: getaddrinfo ENOTFOUND http://kamerun-it.com/mysql
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:60:26)
--------------------
at Protocol._enqueue (F:\kamerun it\aspi-api\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Protocol.handshake (F:\kamerun it\aspi-api\node_modules\mysql\lib\protocol\Protocol.js:51:23)
at PoolConnection.connect (F:\kamerun it\aspi-api\node_modules\mysql\lib\Connection.js:119:18)
at Pool.getConnection (F:\kamerun it\aspi-api\node_modules\mysql\lib\Pool.js:48:16)
at Object. (F:\kamerun it\aspi-api\app\model\db.js:16:8)
at Module._compile (internal/modules/cjs/loader.js:956:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
at Module.load (internal/modules/cjs/loader.js:812:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Module.require (internal/modules/cjs/loader.js:849:19) {
errno: 'ENOTFOUND',
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'http://kamerun-it.com/mysql',
fatal: true
}
You probably have an error in your config with the host URL.
Here's a working example with a connection to a remote MySQL:
const mysql = require("mysql");
const connection = mysql.createPool({
host: "remotemysql.com",
user: "aKlLAqAfXH",
password: "PZKuFVGRQD",
database: "aKlLAqAfXH"
});
connection.query(
"SELECT hexcode FROM colours WHERE precedence = 2",
(err, result) => {
err ? console.log(err) : console.log(result[0].hexcode);
}
);
and here's one with mistaken host parameter:
const mysql = require("mysql");
const connection = mysql.createPool({
host: "WRONGremotemysql.com",
user: "aKlLAqAfXH",
password: "PZKuFVGRQD",
database: "aKlLAqAfXH"
});
connection.query(
"SELECT hexcode FROM colours WHERE precedence = 2",
(err, result) => {
err ? console.log(err) : console.log(result[0].hexcode);
}
);
The second one returns the same ENOTFOUND error.
Check if that's the correct URL, if the database can be accessed remotely and via which port you can use it.

sql node.js error 10061

I am trying to create my first database with node.js but I cant't connect to the server.It gives me error 1061.I am absolutely new in creating databases and I have no idea where is my mistake.Can someone help me?
Thank you!
Here is my code:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
const http = require('http');
var qs = require('querystring');
var url = require('url');
const server = http.createServer();
server.on('request', (request, response) => {
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
console.log(query);
var body = '';
response.setHeader("Access-Control-Allow-Origin", "*");
request.on('data', (chunk) => {
body += chunk;
}).on('end', () => {
var post = qs.parse(body);
console.log(post);
if(query.command == "register") {
con.query("INSERT INTO customers (name, email, password)
VALUES(?,?,?)", [post.name, post.email, post.password], function (err, result, fields) {
if (err) throw err;
console.log(result);
});
}
response.statusCode = 200;
response.end();
});
});
server.listen(8080);
Here is the Console output:
C:\Users\HP>node server.js
C:\Users\HP\server.js:11
if (err) throw err;
^
Error: connect ECONNREFUSED 127.0.0.1:3306
at Object._errnoException (util.js:1031:13)
at _exceptionWithHostPort (util.js:1052:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1195:14)
--------------------
at Protocol._enqueue (C:\Users\HP\node_modules\mysql\lib\protocol\Protocol.js:145:48)
at Protocol.handshake (C:\Users\HP\node_modules\mysql\lib\protocol\Protocol.js:52:23)
at Connection.connect (C:\Users\HP\node_modules\mysql\lib\Connection.js:130:18)
at Object.<anonymous> (C:\Users\HP\server.js:10:5)
at Module._compile (module.js:641:30)
at Object.Module._extensions..js (module.js:652:10)
at Module.load (module.js:560:32)
at tryModuleLoad (module.js:503:12)
at Function.Module._load (module.js:495:3)
at Function.Module.runMain (module.js:682:10)
This error means that node.js can't connect to your MySQL server.
Most likely your MySQL server not started at all.

Node Js : MYSQL is not connecting

I am new to node.js, so i am stuck at this point. I have tried to learn it from these sites Code Mentor and Github
Till now i have done this :
var mysql = require('mysql');
var app = express();
// Database operations
var connection = mysql.createConnection({
host : 'localhost',
port : '8888',
user : 'sharad',
password : 'teks',
dbName : 'FirstDataBase'
});
connection.connect(function (error) {
if (error){
console.error('error connecting :' + error.stack);
return;
}
console.log('Connected as id :'+ connection.threadId);
});
app.get("/",function(request,response){
console.log(' saving');
var post = {from:'me', to:'you', msg:'hi'};
connection.query('INSERT INTO FirstDataBase SET ?', post, function(err, result) {
if (err) throw err;
});
});
app.get("/",function(request,response){
connection.query('SELECT * from FirstDataBase', function(err, rows, fields) {
connection.end();
if (!err)
console.log('The solution is: ', rows);
else
console.log('Error while performing Query.');
});
});
app.listen(8888);
I can not see any log i am printing in my code. Any help would be appreciated. Thanks
Edits :
Error i get if i remove last line app.listen(8888);
error connecting :Error: connect ECONNREFUSED 127.0.0.1:8888
at Object.exports._errnoException (util.js:907:11)
at exports._exceptionWithHostPort (util.js:930:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1077:14)
--------------------
at Protocol._enqueue (/Users/Admin/IdeaProjects/FirstNodeJS/node_modules/mysql/lib/protocol/Protocol.js:141:48)
at Protocol.handshake (/Users/Admin/IdeaProjects/FirstNodeJS/node_modules/mysql/lib/protocol/Protocol.js:52:41)
at Connection.connect (/Users/Admin/IdeaProjects/FirstNodeJS/node_modules/mysql/lib/Connection.js:136:18)
at Object.<anonymous> (/Users/Admin/IdeaProjects/FirstNodeJS/app.js:40:12)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
I resolve this issue like this
install mysql:
npm install mysql
var mysql = require('mysql');
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
port: '8888', /* port on which phpmyadmin run */
password: 'root',
database: 'dbname',
socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock' //for mac and linux
});
connection.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
I resolved my problem by installing MAMP and using fields provided by MAMP.
try this
var connection = mysql.createConnection({
host : 'localhost',
user : 'xxxxx',
password : 'xxxxx',
database : 'xxx'
});
connection.connect();

unable to connect mysql in node js

my script is here
var mysql= require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '12345',
database: 'mydb'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
when i running this code it shows this error
error connecting: Error: connect ETIMEDOUT
at Connection._handleConnectTimeout (~/node_modules/mysql/lib/Connection.js:414:13)
at Socket.g (events.js:180:16)
at Socket.EventEmitter.emit (events.js:92:17)
at Socket._onTimeout (net.js:327:8)
at Timer.unrefTimeout [as ontimeout] (timers.js:412:13)
--------------------
at Protocol._enqueue (~/mysql/lib/protocol/Protocol.js:141:48)
at Protocol.handshake (~/node_modules/mysql/lib/protocol/Protocol.js:52:41)
at Connection.connect (~/node_modules/mysql/lib/Connection.js:125:18)
at Object.<anonymous> (~/Desktop/Node-Eclipse/server.js:10:12)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
Username and password and all other details are correct
I'm using an export that works exactly like your function and it works properly..
var mysql = require("mysql");
var self = module.exports = {
db:{},
init: function(login, callback) {
self.db = mysql.createConnection({
host:'myHost',
user:'myUser',
password:'myPassword',
database:'myDbName'
});
return self.db.connect(function(err) {
if (err) {
callback(null);
}
else {
callback(self.db);
}
});
},
execute:function(login, request, callback) {
return self.db.query(request, function(err, rows, fields) {
if (err) {
callback(null);
}
else {
callback(rows);
}
});
}
};
Please pass port number which is 3306 in your mysql connection

error connecting/querying mysql node.js and postreSQL

the mysql/node.js appears to connect then i "think" there may be a problem with the query event logic. Here's the code and error. I also have a separate/similar problem with postreSQL. I install npmed both in the same directory.
ryan#\Ryan:~/Desktop/node/datastores$ node MySQL
connection::connected
/home/ryan/Desktop/node/datastores/MySQL.js:20
if (err) throw err;
^
Error: connect ECONNREFUSED
at errnoException (net.js:901:11)
at Object.afterConnect [as oncomplete] (net.js:892:19)
--------------------
at Protocol._enqueue (/home/ryan/Desktop/node/node_modules/mysql/lib/protocol/Protocol.js:135:48)
at Protocol.handshake (/home/ryan/Desktop/node/node_modules/mysql/lib/protocol/Protocol.js:52:41)
at Connection.connect (/home/ryan/Desktop/node/node_modules/mysql/lib/Connection.js:123:18)
at Object.<anonymous> (/home/ryan/Desktop/node/datastores/MySQL.js:15:12)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
this is my server/mysql logic
var mysql = require('mysql');
var connectionConfig = {
host: 'localhost',
user: 'root',
password: '',
database: 'sakila'
};
var connection = mysql.createConnection( connectionConfig);
connection.connect(function(err) {
console.log('connection::connected');
});
connection.query('SELECT * FROM actor', function(err, rows, fields) {
if (err) throw err;
rows.forEach(function(row) {
console.log(row.first_name, row.last_name);
});
});
var actor = { first_name: 'Wil', last_name: 'Wheaton' };
connection.query('INSERT INTO actor SET ?', actor, function(err, results) {
if (err) throw err;
console.log(results);
});
connection.end(function(err) {
console.log('connection::end');
});
heres postre logic
var pg = require('pg');
var connectionString = 'postgres://ryan#localhost/postgres';
var client = new pg.Client(connectionString);
client.connect(function(err) {
if (err) throw err;
client.query('SELECT NOW() AS "THE TIME"', function( err, result ) {
if (err) throw err;
console.log(result.rows[0]);
client.end();
});
});
heres error
ryan#\Ryan:~/Desktop/node/datastores$ node postreSQL
/home/ryan/Desktop/node/datastores/postreSQL.js:8
if (err) throw err;
^
Error: connect ECONNREFUSED
at errnoException (net.js:901:11)
at Object.afterConnect [as oncomplete] (net.js:892:19)
Your password seems to be empty in both connections.
You need to get the connection details for the database from your devOps / SysAdmin / whoever created it.
Ask for the hostname, port, user and password, and schema name; then put those in your init object:
// MySQL:
var connectionConfig = {
host: "", // Hostname + ":" + port (no need for :port if 3360)
user: "", // User
password: "", // Password
database: "" // Schema
};
// PostgreSQL:
var connectionString = 'postgres://user:password#hostname:port';