Connection to postgresql db from node js - node.js

I'm tyring to make a connection from my nodejs script to my db connection, but seems like there is a suspicius issue i'm not able to figure out.
At the moment, this is my code:
const { Pool } = require('pg');
const pool = new Pool({
user: 'user',
host: '192.168.1.xxx',
database: 'database',
password: 'password',
port: 5432,
});
pool.on('error', (err, client) => {
console.error('Error:', err);
});
const query = `SELECT * FROM users`;
pool.connect()
.then((client) => {
client.query(query)
.then(res => {
for (let row of res.rows) {
console.log(row);
}
})
.catch(err => {
console.error(err);
});
})
.catch(err => {
console.error(err);
});
The issue seems to be in pool.connect(), but i can't understand what i'm missing because i got no errors in the log. I've installed pg module in the directory of my project with npm install --prefix pg and i know modules are loaded correctly.
I edited postgresql.conf:
# - Connection Settings -
listen_addresses = '*'
and pg_hba.conf
host database user 192.168.1.0/24 md5
to make the database reachable via lan and seems liek it works, because i'm able to connect successfully with apps like DBeaver...but i can't with NodeJS.
It's possible there is some kind of configuration i've to active?

Related

Failed to connect SQL Server from Node.js using tedious

I am trying to connect to SQL Server in our domain network. I am able to connect using python but not able to connect in Node.js using Tedious.
Node.js code snippet:
var config = {
server: 'serverName.domain.com',
authentication: {
type: 'default',
options: {
userName: 'DOMAINID\\username',
password: 'password'
}
},
options: {
database: 'dbName',
port: 1234,
}
};
var connection = new Connection(config);
connection.on('connect', function (err) {
if (err) {
console.log('err', err);
} else {
console.log("Connected");
executeStatement();
}
});
connection.connect();
Receiving error:
Login Failed for the user DOMAINID/username. The login is from an untrusted domain and cannot be used with Windows authentication.
But when trying to connect from Python, I am able to connect successfully.
Python snippet:
import sqlalchemy
conn = sqlalchemy.create_engine('mssql+pymssql://DOMAINID\\username:password#serverName.domain.com:1234/dbName')
print(conn.execute('SELECT * FROM table_name').fetchall())
Data received successfully in python.
And also I tried with mssql and msnodesqlv8 with Microsoft ODBC 11 for Microsoft SQL Server drivers.
I am able to connect. Following is the code snippet.
const sql = require("mssql/msnodesqlv8");
const main = async () => {
const pool = new sql.ConnectionPool({
server: "server.domain.com",
database: "dbName",
port: 1234,
user:'DomainId\\username', // Working without username and password
password:'password',
options: {
trustedConnection: true // working only with true
}
});
await pool.connect();
const request = new sql.Request(pool);
const query = 'select * from table';
const result = await request.query(query);
console.dir(result);
};
main();
In the above snippet, I am able to connect without username and password but with trustedConnection true only. I am using windows authentication not SQL authentication. How can I connect using tedious js

Failed to connect to mydb.database.windows.net:1433 in 15000ms (Microsoft Azure SQL Database)

I am able to retrieve data from Microsoft Azure SQL Database using below code: -
const sql = require("mssql");
var config = {
user: "user_name",
password: "Pass#1234",
server: "mydb.database.windows.net",
database: "db_name",
options: {
enableArithAbort: true,
},
stream: true,
};
module.exports = function getQueryResult(query) {
return new Promise((res, rej) => {
sql.connect(config).then((pool) => {
pool.query(query, (err, result) => {
if (err) rej(err);
res(result);
});
});
});
};
I am using getQueryResult function to get the data from database.
Everything is going perfect accept the thing that the below errors occurs in between.
Failed to connect to mydb.database.windows.net:1433 in 15000ms (Microsoft Azure SQL Database)
ConnectionError: Failed to connect to mydb.database.windows.net:1433 read ECONNRESET
ConnectionError: Failed to connect to mydb.database.windows.net:1433 socket hang up
I know this question has been asked before. But I have tried all the solutions. None of the solution was specifically for Microsoft Azure SQL Database so I thought might be there is some problem in database.
Thanks in advance.
Your code is a bit different from mine, my options is enclosed in double quotes. You also can download my sample code, it works for me, I have test it.
Tips:
You need set the rule of Firewalls. Make sure your local or webapp can access dbserver.
My code:
const sql = require('mssql')
const config = {
user: 'username',
password: 'pwd',
server: '***sqlserver.database.windows.net', // You can use 'localhost\\instance' to connect to named instance
database: 'yourdb',
"options": {
"encrypt": true,
"enableArithAbort": true
}
}
const poolPromise = new sql.ConnectionPool(config)
.connect()
.then(pool => {
console.log('Connected to MSSQL')
return pool
})
.catch(err => console.log('Database Connection Failed! Bad Config: ', err))
module.exports = {
sql, poolPromise
}

How to add proxy to connect with Azure Postgresql?

I use this script to connect node.js with Azure Postgresql.
But the ssl verification of our firewall blocks the connection, so in the past I need to use a proxy. Where in the code can I add the proxy settings as like host and port?
Means when I start the code, vscode should connect through the proxy to postgresql.
const pg = require('pg');
const config = {
host: '<your-db-server-name>.postgres.database.azure.com',
// Do not hard code your username and password.
// Consider using Node environment variables.
user: '<your-db-username>',
password: '<your-password>',
database: '<name-of-database>',
port: 5432,
ssl: true
};
const client = new pg.Client(config);
client.connect(err => {
if (err) throw err;
else { queryDatabase(); }
});
function queryDatabase() {
console.log(`Running query to PostgreSQL server: ${config.host}`);
const query = 'SELECT * FROM inventory;';
client.query(query)
.then(res => {
const rows = res.rows;
rows.map(row => {
console.log(`Read: ${JSON.stringify(row)}`);
});
process.exit();
})
.catch(err => {
console.log(err);
});
}
To configure proxy for Visual Studio Code
Edit the settings.json file
Depending on your platform, the user settings file is located here:
Windows: %APPDATA%\Code\User\settings.json
macOS: $HOME/Library/Application Support/Code/User/settings.json
Linux: $HOME/.config/Code/User/settings.json
Modify and Add the below lines to configure your proxy
"http.proxy": "http://user:pass#proxy.com:portnumber",
"https.proxy": "http://user:pass#proxy.com:portnumber",
"http.proxyStrictSSL": false
If your proxy doesn't require authentication, you could simply use
"http.proxy": "http://proxy.com:portnumber",
"https.proxy": "http://proxy.com:portnumber"
"http.proxyStrictSSL": false
Restart VS Code
The documentation related to settings and schema of the settings.json file is here for reference

Exception handling not working for PG npm package

I installed "pg": "^8.0.2" and created the database.js file with database credentials. But no matter what go wrong it never enters in the catch block to show error. Instead it always logs connected to the database. Can anyone point out what I'm doing wrong. Thank You!
Database.js
const Pool = require('pg').Pool;
const pool = new Pool({
user: 'roothjk',
host: 'localhost',
database: 'sf',
password: 'admin',
port: 5432
});
try {
pool.connect()
console.log('connected to the db');
} catch (e) {
console.log('Error connecting to db');
}
connect returns a Promise, and then you move to the next statement. Instead, you should use the then and cath methods:
pool.connect()
.then(c => console.log('connected to the db'))
.catch(e => console.log('Error connecting to db'));

How to handle error of closed MySQL connection in Node.js?

I've built a Node.js API that connects to a MySQL database. I use node-mysql2 as driver. The API and the database run in separate Docker container. At some point after deployment in a Kubernetes cluster I get the following error:
Error: Can't add new command when connection is in closed state
at PromiseConnection.query (/usr/src/app/node_modules/mysql2/promise.js:92:22)
I wonder why this error happens and how to catch and handle it using Node.js. These are code snippets of my Node.js API:
const mysql = require('mysql2/promise')
...
async function main() {
try {
const client = await mysql.createConnection({
host: DATABASE_HOST,
port: DATABASE_PORT,
user: DATABASE_USERNAME,
password: DATABASE_PASSWORD,
database: DATABASE_NAME
})
client.on('error', error => {
process.stderr.write(`${error.code}\n`) // PROTOCOL_CONNECTION_LOST
process.stderr.write(`An error occurred while connecting to the db: ${error.message}\n`)
process.exit(1)
})
} catch (error) {
process.stderr.write(`Error while creating db connection: ${error.code}\n`)
}
...
}
...
main().catch(err => {
process.stderr.write(`Error message: ${err.message}\n`)
process.exit(1)
})
Do you have an idea how to handle this error?
Do you close the connection after finishing with it?
client.end();
Also considered using a pool?
const pool = mysql.createPool({
host: DATABASE_HOST,
user: DATABASE_USERNAME,
database: DATABASE_NAME,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
More info about pools: https://github.com/sidorares/node-mysql2#using-connection-pools

Resources