I have an issue that maybe someone can help me with:
I'm trying to build a nodeJS server, working from my laptop, using node-mysql, and trying to make a remote connection to my database.
function foo (callback) {
// Connect to the database
var mysql = require('mysql');
var connection = mysql.createConnection({
host: <ipaddress>,
user: "test_developer",
password: "test_developer",
database: "test3"
});
connection.connect(function(err){
if (err){
console.log("cannot connect to database");
console.log(err);
}
else
{
console.log("connected to database");
}
});
};
// Implementation
foo(function(err, result){
console.log("Never made it here");
});
This times out with:
cannot connect to database
{ [Error: connect ETIMEDOUT]
code: 'ETIMEDOUT',
errno: 'ETIMEDOUT',
syscall: 'connect',
fatal: true
}
I believe the database is ok, I can connect with phpMyAdmin from browser.
What am I doing wrong?
Related
I have a connection on DBeaver using an ssh tunnel as follows:
sshHostname;
sshPort;
sshUser;
sshPassword;
on the actual connection to the database I have:
dbHost;
dbPort;
dbName;
dbUsername;
dbPassword;
my node js code looks something like this:
const { Pool, Client } = require('pg')
const ssh2 = require('ssh2');
const dbServer = {
host: dbHost,
port: dbPort,
database: dbName,
username: dbUser,
password: dbPassword
}
var c = new ssh2();
c.connect({
host: sshHostname,
port: 22,
username: sshUser,
password: sshPassword
});
c.on('ready', function () {
c.forwardOut(sshHostname, '22', dbHost, dbPort , function(err, data) {
const client = new Client({
host: 'localhost',
port: dbPort,
database: dbName,
user: dbUser,
password: dbPassword,
})
client.connect(function (err) {
if (err) {console.log(err)}
else {console.log('connected...')}
});
client.end();
})
});
I get the following error:
Error: connect ECONNREFUSED 127.0.0.1:dbPort
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1133:16) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: dbPort
}
I tried various configurations and various libraries with no success.
do you have any idea how to connect via nodejs to a database over a tunnel?
I have a feeling that I am actually not connecting to the ssh tunnel.
It could various of reasons why there is a connection refusion.
When making connections via SSH, you should have a SSH key ready on your computer and make it a part of your SSH white list. This is a common error many developers may run into, but since your critical information is hidden, we may need you to provide more details in that regard.
I am trying to make a connection to Postgres remote host using the SSH tunnel from node application(library:ssh2) and query the data(lib:pg).
Before I used mysql2(node library) make a tunnel using ssh2(node library) and connected to Mysql remote host as well as able to query the data. But I want to do the same in Postgres remote host I am not able to connect to it.
pg Client obj config does not support the stream from ssh2 forwardOut..!
Or, Is there any library available to make this happen instead of that ssh2, pg
PS: In mysql2 when I try to make a connection with a mysql config with stream: stream key value.
var Clientssh = require('ssh2').Client;
var conn = new Clientssh();
conn.on('ready', function() {
console.log('Client :: ready');
conn.forwardOut(
'127.0.0.1',
5434,
'localhost',
5432,
function(err, stream) {
if (err) throw err;
let conf = {
host: 'localhost',
port: 5434,
user: 'test',
database: 'test',
password: 'test'
}
let remoteConnection = new Client(conf);
remoteConnection.connect(function(err) {
if (err) {
console.log(err);
console.log("Unable to connect to postgre");
res.send(err);
} else {
remoteConnection.query('SELECT * FROM test', function(err, testResult) {
remoteConnection.end();
if (err) {
console.log("Unable to fetch data");
res.send(err);
} else {
console.log("Succcess");
res.send(testResult);
}
});
}
});
});
}).connect({
host: 'hostaddress',
port: 'hostport',
username: 'hostusername',
privateKey: require('fs').readFileSync('path/for/key')
});
It shows the Connection terminated unexpectedly from this line
Client :: ready
Error: Connection terminated unexpectedly
at Connection.con.once (/node-postgres/node_modules/pg/lib/client.js:235:9)
at Object.onceWrapper (events.js:286:20)
at Connection.emit (events.js:198:13)
at Channel.<anonymous> (/node-postgres/node_modules/pg/lib/connection.js:131:10)
at Channel.emit (events.js:203:15)
at endReadableNT (_stream_readable.js:1129:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
Unable to connect to postgre
I have recently deployed my node.js API application on live server. I am getting these issue on live server.
I have googled it, but could not get any exact solution. Can anyone suggest how can i solve this problem?
{ Error: read ETIMEDOUT at TCP.onread (net.js:622:25) errno: 'ETIMEDOUT', code: 'ETIMEDOUT', syscall: 'read', fatal: true }
{ Error: Can't add new command when connection is in closed state at PoolConnection._addCommandClosedState }
I amd using the mysql connection pool like this
var mysql = require('mysql2');
var mysqlPool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'xyz',
database: 'xyz',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
module.exports = mysqlPool;
I had a similar problem and ended up having to put the connection request in it's own .js file and import it into the controller-
connectionRequest.js
module.exports = function () {
let mysql = require('mysql2')
let connCreds = require('./connectionsConfig.json');
//Establish Connection to the DB
let connection = mysql.createConnection({
host: connCreds["host"],
user: connCreds['username'],
password: connCreds['password'],
database: connCreds['database'],
port: 3306
});
//Instantiate the connection
connection.connect(function (err) {
if (err) {
console.log(`connectionRequest Failed ${err.stack}`)
} else {
console.log(`DB connectionRequest Successful ${connection.threadId}`)
}
});
//return connection object
return connection
}
Once I did that I was able to import it into my query on the controller file like so
ControllerFile.js
let connectionRequest = require('../config/connectionRequest')
controllerMethod: (req, res, next) => {
//Establish the connection on this request
connection = connectionRequest()
//Run the query
connection.query("SELECT * FROM table", function (err, result, fields) {
if (err) {
// If an error occurred, send a generic server failure
console.log(`not successful! ${err}`)
connection.destroy();
} else {
//If successful, inform as such
console.log(`Query was successful, ${result}`)
//send json file to end user if using an API
res.json(result)
//destroy the connection thread
connection.destroy();
}
});
},
After a lot of messing around I was able to solve the problem by destroying the connection, waiting (this is the important page) and getting the connection again.
conn = await connPool.getConnection();
// We have error: Can't add new command when connection is in closed state
// I'm attempting to solve it by grabbing a new connection
if (!conn || !conn.connection || conn.connection._closing) {
winston.info('Connection is in a closed state, getting a new connection');
await conn.destroy(); // Toast that guy right now
sleep.sleep(1); // Wait for the connection to be destroyed and try to get a new one, you must wait! otherwise u get the same connection
conn = await connPool.connection.getConnection(); // get a new one
}
I'm using node.js and the mssql package to connect to a SQL Server database using SQL Server authentication. When I try connecting using SQL Server Management Studio with the same credentials, it is working fine. However, with node.js, I cannot login and get an error code ELOGIN with connection error.
I've tried many examples shown in google and I'm facing the same issue.
Let me know what I'm missing. Here is the code snippet of mine.
Code starts here
var sql = require('mssql');
var config = {
server: 'scaXXXXXXXXXXXX',
database: 'scaXXXXXXXXXX',
user: 'svcXXXXXXX',
password: 'Password',
port: 1433
};
function listProducts() {
var conn = new sql.ConnectionPool(config);
conn.connect().then(function () {
var request = new sql.Request(conn);
request.query("select top 1 * from dbo.Persons").then(function
(recordSet) {
console.log(recordSet);
conn.close();
}).catch(function (err) {
console.log(err);
conn.close();
});
}).catch(function (err) {
console.log(err);
});
}
listProducts();
This is the error while running this code:
ConnectionError: Login failed for user 'svcXXXXXXX'.
at Connection.tedious.once.err (C:\aws\node_modules\mssql\lib\tedious.js:244:17)
at Object.onceWrapper (events.js:277:13)
at Connection.emit (events.js:189:13)
at Connection.processLogin7Response (C:\aws\node_modules\tedious\lib\connection.js:1397:14)
at Connection.message (C:\aws\node_modules\tedious\lib\connection.js:1932:14)
at Connection.dispatchEvent (C:\aws\node_modules\tedious\lib\connection.js:1084:36)
at MessageIO.messageIo.on (C:\aws\node_modules\tedious\lib\connection.js:984:14)
at MessageIO.emit (events.js:189:13)
at Message.message.on (C:\aws\node_modules\tedious\lib\message-io.js:32:14)
at Message.emit (events.js:194:15)
code: 'ELOGIN',
originalError: { ConnectionError: Login failed for user 'svcXXXXXXX'.
at ConnectionError (C:\aws\node_modules\tedious\lib\errors.js:13:12)
at Parser.tokenStreamParser.on.token (C:\aws\node_modules\tedious\lib\connection.js:735:29)
at Parser.emit (events.js:189:13)
at Parser.parser.on.token (C:\aws\node_modules\tedious\lib\token\token-stream-parser.js:27:14)
at Parser.emit (events.js:189:13)
at addChunk (C:\aws\node_modules\readable-stream\lib_stream_readable.js:297:12)
at readableAddChunk (C:\aws\node_modules\readable-stream\lib_stream_readable.js:279:11)
at Parser.Readable.push (C:\aws\node_modules\readable-stream\lib_stream_readable.js:240:10)
at Parser.Transform.push (C:\aws\node_modules\readable-stream\lib_stream_transform.js:139:32)
at doneParsing (C:\aws\node_modules\tedious\lib\token\stream-parser.js:80:14)
message: 'Login failed for user \'svcXXXXXXX\'.',
code: 'ELOGIN' }, name: 'ConnectionError' }
I expect one record from database should extract and display.
it looks your login information is not correct.
did you write proper user name and password?
if your login info is correct, then check out login info has authority to be connected from the external environment
Try this out. It worked for me. If you are not doing with a localhost Database you need to be in that network. Make sure you can ping the database server.
var sql = require("mssql");
var moment = require("moment");
let port = process.env.PORT;
if (port == null || port == "") {
port = 8000;
}
var config = {
user: "xxxx",
password: "xxxxx",
server: "xxxxxx",
database: "xxxx"
};
const dbconn = 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 ");
}
});
app.get("/getSummaryDetails", (req, res) => {
dbconn.query("exec QCGrid", (err, rows, fields) => {
if (!err) {
res.send(rows.recordsets[0]);
}
});
});
I am trying to learn Node.js and created a simple project to query the local database. But I get failed to look up an instance error message.
I have checked that the SQL Server services running in services.msc
I have verified TCP/IP is enabled
I have tried with the username and password and without it as well. I connect to localdb in SQL Server Management Studio as (localdb)\v11.0 and below is the screenshot of the properties
What am I doing incorrectly? What should be actual username and password? What should be the servername?
const sql = require('mssql');
// config for your database
const config = {
user: 'mywindows username',
password: 'my windows password',
server: '(localdb)\\v11.0',
database: 'test',
options: {
encrypt: true
}
};
console.log('starting sql');
var connection = new sql.connect(config, function(err) {
console.log(err);
var request = new sql.Request(connection);
request.query('select * from employees', function(err, recordset) {
if(err) // ... error checks
console.log('Database connection error');
console.dir("User Data: "+recordset);
});
});
sql.close();
console.log('ending sql');
});
app.listen(3002, () => {
console.log('Listening on port 3002');})
Below is the error message
{ ConnectionError: Failed to lookup instance on (localdb) -
getaddrinfo ENOTFOUND (localdb)
at Connection.tedious.once.err (C:\Users\vndbsubramaniam\Desktop\React
projects\ReactWithSql\node_modules\mssql\lib\tedious.js:244:17)
at Object.onceWrapper (events.js:285:13)
at Connection.emit (events.js:197:13)
at InstanceLookup.instanceLookup (C:\Users\vndbsubramaniam\Desktop\React
projects\ReactWithSql\node_modules\tedious\lib\connection.js:945:16)
at sender.execute (C:\Users\vndbsubramaniam\Desktop\React projects\ReactWithSql\node_modules\tedious\lib\instance-lookup.js:66:13)
at GetAddrInfoReqWrap.invokeLookupAll [as callback] (C:\Users\vndbsubramaniam\Desktop\React
projects\ReactWithSql\node_modules\tedious\lib\sender.js:43:16)
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (dns.js:70:17) code: 'EINSTLOOKUP', originalError: { ConnectionError: Failed to
lookup instance on (localdb) - getaddrinfo ENOTFOUND (localdb)
at ConnectionError (C:\Users\vndbsubramaniam\Desktop\React projects\ReactWithSql\node_modules\tedious\lib\errors.js:13:12)
at InstanceLookup.instanceLookup (C:\Users\vndbsubramaniam\Desktop\React
projects\ReactWithSql\node_modules\tedious\lib\connection.js:945:32)
at sender.execute (C:\Users\vndbsubramaniam\Desktop\React projects\ReactWithSql\node_modules\tedious\lib\instance-lookup.js:66:13)
at GetAddrInfoReqWrap.invokeLookupAll [as callback] (C:\Users\vndbsubramaniam\Desktop\React
projects\ReactWithSql\node_modules\tedious\lib\sender.js:43:16)
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (dns.js:70:17)
message:
'Failed to lookup instance on (localdb) - getaddrinfo ENOTFOUND (localdb)',
code: 'EINSTLOOKUP' }, name: 'ConnectionError' } Database connection error
After struggling for hours on this one finally found the answer here SQL to Node connection
It seems i have to add msnodesqlv8 package and use add the driver syntax to the config.
app.get('/test', (req, res) => {
const sql = require('mssql/msnodesqlv8');
// config for your database
const config = {
database: 'test',
server: '(localdb)\\v11.0',
driver: 'msnodesqlv8',
options : {
trustedConnection : true
}
};
console.log('starting sql');
const pool = new sql.ConnectionPool(config);
pool.connect().then(() => {
//simple query
pool.request().query('select * from employees', (err, result) => {
if(err) res.send(err)
else{
return res.json({
data : result.recordset
})
}
})
sql.close();
})
console.log('ending sql');
});
you will need msnodesqlv8 driver, which you have to paste it in require as
var sql = require('mssql/msnodesqlv8'),
as well as you will have to include it in driver section in config object.
var config = {
user:"*****",
password:"*****",
database:"*****",
driver: 'msnodesqlv8',
server:"*****",
options: {
trustedConnection : true
}
}