can't get mysql module to work with node js - javascript

I am compleeeeetly new to Node js and wanted to start my very first project to get used to it. I am using the excess framework.
I found some nice mysql module which was easily downloaded and installed. The module is correctly placed in the modules folder.
I tried to call it in my app.js file like that:
...
var mysql = require('mysql');
...
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '27sparks&&55',
database : 'react'
});
connection.connect();
app.locals.mysql = connection;
connection.query('SELECT * FROM comment', function(err, rows, fields) {
if (err) throw err;
console.log(rows);
});
connection.end();
When I try to run the www in the /bin directory with this command : node www to start my localhost project I now get following error in the terminal:
/Applications/XAMPP/xamppfiles/htdocs/nodeschool/learn/app.js:79
if (err) throw err;
^
Error: connect ECONNREFUSED 127.0.0.1:3306
at Object.exports._errnoException (util.js:837:11)
at exports._exceptionWithHostPort (util.js:860:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1060:14)
--------------------
at Protocol._enqueue (/Applications/XAMPP/xamppfiles/htdocs/nodeschool/learn/node_modules/mysql/lib/protocol/Protocol.js:135:48)
at Protocol.handshake (/Applications/XAMPP/xamppfiles/htdocs/nodeschool/learn/node_modules/mysql/lib/protocol/Protocol.js:52:41)
at Connection.connect (/Applications/XAMPP/xamppfiles/htdocs/nodeschool/learn/node_modules/mysql/lib/Connection.js:123:18)
at Object.<anonymous> (/Applications/XAMPP/xamppfiles/htdocs/nodeschool/learn/app.js:75:12)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)

Try getting feedback from the connect line (code taken from here) :
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);
});
Also, try setting the port to 3306 manually, even though it defaults to it.
Stupid questions worth asking : is your MySQL instance up and running ? Is it listening on the good port ? Is the password correct ?

you are probably trying to connect to the wrong socket
add a socketPath to your create connection option object like this
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '27sparks&&55',
database : 'react',
socketPath : 'path/to/your/mysqlsocket' // /*example: /var/run/mysqld/mysqld.sock on ubuntu*/
});

Related

sql not connecting in node js

I'm trying to connect my database with node js but it is giving me this error .
here is my code
//to connect to sql
var mysql=require('mysql');
var conn=mysql.createConnection({
host:"localhost",
user:"root",
password:"",
database:"bns"
});
conn.connect(function (err) {
if (err) {
console.log(err);
return;
}
console.log("connected");
conn.query("SELECT * FROM employee", function (err, recordset) {
if (err) {
console.log(err);
}
else {
console.log(recordset);
}
conn.close();
});
});
and I'm getting this error
Error: connect ECONNREFUSED ::1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1157:16)
--------------------
at Protocol._enqueue (C:\Users\DELL\OneDrive\Desktop\node-demo\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Protocol.handshake (C:\Users\DELL\OneDrive\Desktop\node-demo\node_modules\mysql\lib\protocol\Protocol.js:51:23)
at Connection.connect (C:\Users\DELL\OneDrive\Desktop\node-demo\node_modules\mysql\lib\Connection.js:116:18)
at Object. (C:\Users\DELL\OneDrive\Desktop\node-demo\other.js:11:6)
at Module._compile (node:internal/modules/cjs/loader:1097:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47 {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 3306,
fatal: true
}
[nodemon] clean exit - waiting for changes before restart
I've had an exactly same issue.
var conn=mysql.createConnection({
host:"127.0.0.1",
user:"root",
password:"",
database:"bns"
});
try this code. I think it will work.
Now only problem i hav is why it works.. lol
You should specify the port number by which the server has to establish a connection. In your case, you had missed the port number. The code below must eliminate the problem.
var conn=mysql.createConnection({
host:"localhost",
user:"root",
password:"",
port: 3306,
database:"bns"
});

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");
}
});

Hapijs server start error - Invalid server options

I am using this simple server program
const Hapi = require('hapi');
const server = new Hapi.Server({
host: 'localhost',
port: 8080,
});
server.route({
path: '/',
method: 'GET',
handler: (request, response) => {
response(true);
},
});
server.start(() => {
console.log('Server running at:', server.info.uri);
});
which gave me the following error on server startup
throw new Error(msgs.join(' ') || 'Unknown error');
^
Error: Invalid server options {
"port" [2]: 8080,
"host" [1]: "localhost"
}
[1] "host" is not allowed
[2] "port" is not allowed
at Object.exports.assert (/Users/aakashverma/Documents/exercises/makeithapi/node_modules/hoek/lib/index.js:736:11)
at Object.exports.apply (/Users/aakashverma/Documents/exercises/makeithapi/node_modules/hapi/lib/schema.js:17:10)
at new module.exports.internals.Server (/Users/aakashverma/Documents/exercises/makeithapi/node_modules/hapi/lib/server.js:32:22)
at Object.<anonymous> (/Users/aakashverma/Documents/exercises/makeithapi/serveEm/serveEm.js:3:16)
at Module._compile (module.js:660:30)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Function.Module.runMain (module.js:701:10)
and my package.json has dependencies set this way
"dependencies": {
"axios": "^0.17.1",
"hapi": "^16.6.2"
}
I tried searching for this issue everywhere and found an exact one here but the versions are too old to be compared.
How do I resolve this problem?
The options you're passing need to be passed to a call to server.connection() rather than into the Server constructor.
Snippet from hapi docs:
'use strict';
const Hapi = require('hapi');
const server = new Hapi.Server();
server.connection({ port: 3000, host: 'localhost' });
server.start((err) => {
if (err) {
throw err;
}
console.log(`Server running at: ${server.info.uri}`);
});
Could it be typo issue ?
Because in their sample code here they spelled server with lowercase, and you create a new instance while the sample is just using the function.
// Create a server with a host and port
const server = Hapi.server({
host: 'localhost',
port: 8000
});
Update:
Apparently, the current version for hapi is 17, and the question is asked for 16. So, the details of how to configure a server in version 16.6.2 can be found below:
https://hapijs.com/api/16.6.2

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).

access denied while connecting to mysql through node.js

i am trying to connect to mysql server (host : localhost) through node.js, i am really new to node.js and i have no idea on how to do this, please help!!!
current code which i am using to connect to the server
var client = require('socket.io').listen(8080).sockets,
mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'testDatabase',
port : '3306'
});
connection.connect();
var strQuery = 'select * from users';
connection.query( strQuery, function(err, rows){
if(err){
throw err;
}else{
console.log(rows);
}
});
connection.end();
which apparently gives the below error
Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'prashanthsun9'#'localhost
' (using password: YES)
at Handshake.Sequence._packetToError (C:\wamp\www\node_chat\js\node_modules\
mysql\lib\protocol\sequences\Sequence.js:30:14)
at Handshake.ErrorPacket (C:\wamp\www\node_chat\js\node_modules\mysql\lib\pr
otocol\sequences\Handshake.js:99:18)
at Protocol._parsePacket (C:\wamp\www\node_chat\js\node_modules\mysql\lib\pr
otocol\Protocol.js:205:24)
at Parser.write (C:\wamp\www\node_chat\js\node_modules\mysql\lib\protocol\Pa
rser.js:62:12)
at Protocol.write (C:\wamp\www\node_chat\js\node_modules\mysql\lib\protocol\
Protocol.js:37:16)
at Socket.<anonymous> (C:\wamp\www\node_chat\js\node_modules\mysql\lib\Conne
ction.js:73:28)
at Socket.EventEmitter.emit (events.js:95:17)
at Socket.<anonymous> (_stream_readable.js:746:14)
at Socket.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:408:10)
--------------------
at Protocol._enqueue (C:\wamp\www\node_chat\js\node_modules\mysql\lib\protoc
ol\Protocol.js:110:48)
at Protocol.handshake (C:\wamp\www\node_chat\js\node_modules\mysql\lib\proto
col\Protocol.js:42:41)
at Connection.connect (C:\wamp\www\node_chat\js\node_modules\mysql\lib\Conne
ction.js:99:18)
at Object.<anonymous> (C:\wamp\www\node_chat\js\server.js:11: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)
Please help, please help!!!
Your connection is not yet setup when you try your query.
To debug, change this line:
connection.connect();
to
connection.connect(function(err, conn) {
if(err) {
console.log('MySQL connection error: ', err);
process.exit(1);
}
});
So you'll get the error trace of why your connection is not ok.
Try to upgrade your npm mysql version to ^2.1.1.

Categories