Node JS error "getaddrinfo ENOTFOUND" - javascript

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

Related

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

Requesting tables from MS Sql - Node.js web service

I am in need of assistance in terms of generating a request to my Microsoft SQL Server via a web service (Built in Node.js).
To summarize the problem at hand, it is as follows: I am currently logging into a MS Sql Server Management with a windows auth account - that is all find and dandy however, I am now trying to build a web service that allows for selects and transacts of some tables which is where I am running into issues now specifically in terms of logging in and pulling data to the web service.
Code
var express = require('express'); var app = express();
app.get('/',function(req,res) {
const sql = require('mssql');
// Connection Path
const myServerPath = String("xxxx\\WS1SQLEXPRESS");
// Connection String Parameter
const config = {
// User Login Details - Windows Auth or General User Account
user : 'xxxx-xxx\\AdrianH',
password: 'xxxxxx',
// Server path to connect to
server : myServerPath,
// Database
datebase: 'plex',
options : {
trustedConnection: true
}
};
sql.connect(config,function(err) {
if (err) console.log(err);
// Create Request Object
var request = new sql.Request();
// Query the Database
request.query('USE plex; SELECT * FROM [plex].[dbo].[tblWorkCenters]',function(err,recordset) {
if (err) console.log(err)
// send records as response
res.send(recordset);
});
});
});
// Start Server and listen on //http://localhost:8001/
var server = app.listen(3213,function(){
console.log('Server is running...');
});
I have hid sensitive information, here is the error code
{ ConnectionError: Login failed for user ''.
at Connection.tedious.once.err (C:\Users\adrianh\node_modules\mssql\lib\tedious.js:244:17)
at Object.onceWrapper (events.js:286:20)
at Connection.emit (events.js:198:13)
at Connection.processLogin7Response (C:\Users\adrianh\node_modules\tedious\lib\connection.js:1397:14)
at Connection.message (C:\Users\adrianh\node_modules\tedious\lib\connection.js:1932:14)
at Connection.dispatchEvent (C:\Users\adrianh\node_modules\tedious\lib\connection.js:1084:36)
at MessageIO.messageIo.on (C:\Users\adrianh\node_modules\tedious\lib\connection.js:984:14)
at MessageIO.emit (events.js:198:13)
at Message.message.on (C:\Users\adrianh\node_modules\tedious\lib\message-io.js:32:14)
at Message.emit (events.js:203:15)
code: 'ELOGIN',
originalError:
{ ConnectionError: Login failed for user ''.
at ConnectionError (C:\Users\adrianh\node_modules\tedious\lib\errors.js:13:12)
at Parser.tokenStreamParser.on.token (C:\Users\adrianh\node_modules\tedious\lib\connection.js:735:29)
at Parser.emit (events.js:198:13)
at Parser.parser.on.token (C:\Users\adrianh\node_modules\tedious\lib\token\token-stream-parser.js:27:14)
at Parser.emit (events.js:198:13)
at addChunk (C:\Users\adrianh\node_modules\readable-stream\lib\_stream_readable.js:297:12)
at readableAddChunk (C:\Users\adrianh\node_modules\readable-stream\lib\_stream_readable.js:279:11)
at Parser.Readable.push (C:\Users\adrianh\node_modules\readable-stream\lib\_stream_readable.js:240:10)
at Parser.Transform.push (C:\Users\adrianh\node_modules\readable-stream\lib\_stream_transform.js:139:32)
at doneParsing (C:\Users\adrianh\node_modules\tedious\lib\token\stream-parser.js:80:14) message: 'Login failed for user \'\'.', code: 'ELOGIN' },
name: 'ConnectionError' }
{ ConnectionError: Connection is closed.
at Request._query (C:\Users\adrianh\node_modules\mssql\lib\base.js:1399:37)
at Request._query (C:\Users\adrianh\node_modules\mssql\lib\tedious.js:546:11)
at Request.query (C:\Users\adrianh\node_modules\mssql\lib\base.js:1335:12)
at C:\Users\adrianh\Desktop\JEC_Current_Projects\WebService\WCWebServiceIOS.js:30:13
at _poolCreate.then.catch.err (C:\Users\adrianh\node_modules\mssql\lib\base.js:287:7)
at process._tickCallback (internal/process/next_tick.js:68:7) code: 'ECONNCLOSED', name: 'ConnectionError' }
** An interesting note to make is in --
(C:\Users\adrianh\node_modules\tedious\lib\token\stream-parser.js:80:14) message: 'Login failed for user \'\'.', code: 'ELOGIN' },
name: 'ConnectionError' }
It doesn't actually seem to pass my login information - any help will be greatly appreciated thank you.
If you are trying to connect mssql via windows authentication in node JS use this module.
var mssql = require('mssql/msnodesqlv8
Sample:
var mssql = require('mssql/msnodesqlv8')
var dbConfig = {
server: 'server',
driver: 'msnodesqlv8',
database: 'DBDATA',
port: '1433',
options: {
trustedConnection: true,
debug: {
packet: false,
payload: false,
token: false,
data: false
},
}
};

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 ?

Error: Can't set headers after they are sent. node.js

I'm tring to coed an application which lets users execute commands over url but I get this error message:
_http_outgoing.js:346
throw new Error('Can\'t set headers after they are sent.');
^Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:346:11)
at ServerResponse.header (C:\Users\Jarvis\node_modules\express\lib\response.js:718:10)
at ServerResponse.json (C:\Users\Jarvis\node_modules\express\lib\response.js:246:10)
at C:\Users\Jarvis\Desktop\sys.js:9:6
at ChildProcess.exithandler (child_process.js:193:7)
at emitTwo (events.js:100:13)
at ChildProcess.emit (events.js:185:7)
at maybeClose (internal/child_process.js:850:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:215:5)
This is my Code:
var Express = require('express');
var app = Express();
var sys = require('sys');
var exec = require('child_process').exec;
var child;
app.get("/:cmd", function(req, res) {
child = exec(req.params.cmd, function (error, stdout, stderr) {
res.json({"stdout":stdout});
res.json({"stderr": stderr});
if (error != null) {
console.log("exec error: "+error);
}
});
});
app.listen(8080);
You can only call res.json one time per http request.
change
res.json({"stdout":stdout});
res.json({"stderr": stderr});
to:
res.json({"stdout":stdout, "stderr": stderr});

can't get mysql module to work with node js

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*/
});

Categories