Connection fail to SQL Server using NodeJS mssql msnodesqlv8 from the server - node.js

I wrote a little service in NodeJS which connects to SQL Server.
In my local machine, the connection is established successfully.
After putting my files in a remote machine, I get this error:
ConnectionError: [Microsoft][ODBC Driver Manager] Data source name not
found and no default driver specified
I use windows authentication but when the username didn't have permissions, I got a different error.
const mssql = require("mssql/msnodesqlv8");
const mypool = new mssql.ConnectionPool({
driver: 'msnodesqlv8',
server: myhost,
database: mydb,
port: 1443,
options: {
trustedConnection: true,
enableArithAbort: true
}
});
mypool.connect().then(pool => {
console.log('Connected to MSSQL (DB: mydb)');
return pool;
}).catch(err => console.log('Database Connection Failed! Bad Config: ', err))

Try modifying the connection pool as below,
const pool=new sql.ConnectionPool (config, function(err){
if(err){
console.log('Error while creating connection pool \n'+err);
}
});

Related

Why can't my node js script connect to my mssql database running in docker, but Microsoft SQL Server Management can

I'm trying to connect node js script to MsSQL database server, but fails.
My Microsoft SQL Server Management is however able to connect to the database.
node.js code
var Connection = require('tedious').Connection;
var config = {
server: "172.168.200.35",
dialect: "mssql",
port:51433,
authentication: {
type: 'default',
options: {
userName: 'testuser',
password: 'abc123'
}
},
options: {
database: 'IoTDb'
}
};
var connection = new Connection(config);
// Attempt to connect and execute queries if connection goes through
connection.on("connect", err => {
if (err) {
console.error(err.message);
} else {
executeStatement();
}
});
When running the code, I get this error
Failed to connect to 172.168.200.35:51433:1433 - getaddrinfo ENOTFOUND 172.168.200.35:51433
I don't understand why its fails to connect port 1433, as the port is defined as 51433
However, when I try to connect to the database via this login info (same as node config variable)
It connects and I get this view over the database
For info about the database, it is running via docker on another pc, but is reachable
I moved the port to options and now the error is this
Failed to connect to 172.168.200.35:51433:51433 - getaddrinfo ENOTFOUND 172.168.200.35:51433
As this issue shows the port should be specified in options:
var config = {
server: "172.168.200.35",
dialect: "mssql",
...
options: {
database: 'IoTDb',
port:51433,
}
};

Error connecting NodeJS and SQL Server - Could not connect (sequence)

I'm trying to create a connection with SQL Server and NodeJS as shown below (SQL Server installed locally -> localhost):
It's throwing the following error: ERROR: Failed to connect to MY_SERVER:1433 - Could not connect (sequence)
This didn't work either.
I thought it was a problem with the SQL Server installation, but via Python It works well on the same database.
I'm using SQL Server 2019 and latest NodeJS version.
REFERENCE:
https://learn.microsoft.com/en-us/sql/connect/node-js/step-3-proof-of-concept-connecting-to-sql-using-node-js?view=sql-server-ver15
How to fix this error?
var config = {
server: 'MY_SERVER',
authentication: {
type: 'default',
options: {
userName: 'sa',
password: 'admin'
}
},
options: {
encrypt: false, // I've already tried with "true" also.
database: 'MyDataBase'
}
};
var connection = new Connection(config);
connection.on('connect', function(err) {
if (err) {
console.log("Error: ", err.message);
} else {
console.log("Connected");
}
});
connection.connect();
I got it!! Basically, for NodeJS get connection to SQLServer, the TCP/IP Protocol must be enabled for the MSSQLSERVER Instance, in the SQL Server network settings.
Ref.:
Nodejs connection with mssql showing error
https://store.oceansystems.com/knowledgebase/quickdme-faqs/sql-server-sql-express/configure-sql-express-server-host-enable-tcp-ip-firewall-settings/

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

Can't connect to SQL Server from my VS Code extension (node.js)

I'm developing VS Code extension and want to get some data from SQL Server database. I've tried many different examples but non of them are working for me.
const Connection = require('tedious').Connection;
const config = {
user: 'ssrs', // tried userName, username
password: 'ssrs',
server: 'localhost',
options: {
database: 'imdb'
}
}
const connection = new Connection(config);
connection.on('connect', function(err: string) {
if (err) {
console.log(err);
} else {
console.log('Connected');
}
});
OR
await sql.connect('mssql://ssrs:ssrs#localhost/imdb')
const result = await sql.query`select 1 as one`
console.dir(result)
OR
const sql = require("mssql");
const conn = new sql.ConnectionPool({
database: "imdb",
server: "localhost",
driver: "msnodesqlv8",
userName: "ssrs",
password: "ssrs"
});
conn.connect().then(() => {
console.log('Connected');
});
ConnectionError: Login failed for user ''.
Connecting via sqlcmd:
The port is also open (1433) as I can telnet to it.
Messages from SQL Server log:
Date 2019-05-08 11:19:02 AM Log SQL Server (Current - 2019-05-05
2:53:00 PM)
Source Logon
Message Login failed for user ''. Reason: An attempt to login using
SQL authentication failed. Server is configured for Integrated
authentication only. [CLIENT: 127.0.0.1]
Date 2019-05-08 11:19:02 AM Log SQL Server (Current - 2019-05-05
2:53:00 PM)
Source Logon
Message Error: 18456, Severity: 14, State: 58.
Trying to connect with Powershell:
PS C:\WINDOWS\system32> Invoke-Sqlcmd -query "select CURRENT_USER, USER_NAME()" -ServerInstance "localhost" -username "ssrs" -password "ssrs" -Database 'imdb'
Column1 Column2
------- -------
ssrs ssrs
As shown in your screenshot, you're able to connect via SQLCMD utility. This means there's no issue with the user or the authentication mode in SQL Server.
The error message is however misleading and other users already experienced this here.
I'm no expert of node.js but I'd recommend you to better understand how the mssql plugin and Connection object work. I think that some missing setting in your configuration is making the connection attempt fail.
For example, this code you posted is wrong (userName is not valid):
const sql = require("mssql");
const conn = new sql.ConnectionPool({
database: "imdb",
server: "localhost",
driver: "msnodesqlv8",
userName: "ssrs",
password: "ssrs"
});
conn.connect().then(() => {
console.log('Connected');
});
It should be:
const sql = require("mssql");
const conn = new sql.ConnectionPool({
database: "imdb",
server: "localhost",
driver: "msnodesqlv8",
user: "ssrs",
password: "ssrs"
});
conn.connect().then(() => {
console.log('Connected');
});
The reason you can't connect is written in the log:
Reason: An attempt to login using SQL authentication failed. Server is
configured for Integrated authentication only.
You have to change the authentication mode (which you already did according to the screenshot posted) and restart the SQL Server service with Agent. Did you restart the service after changing the mode?

Connecting to SQL server through Node.js

I am trying to connect to sql server from node.js like so -
const sql = require('mssql')
const pool = new sql.ConnectionPool({
database: 'db',
server: 'name',
port: 41041,
driver: 'msnodesqlv8',
options: {
trustedConnection: true,
integratedSecurity: true
}
})
pool.connect().then(() => {
//simple query
pool.request().query('select top 10 * from sync', (err, result) => {
console.dir(result)
})
})
But it is giving me this error - ConnectionError: Failed to connect to name:41041 in 15000ms at Connection.tedious.once.err
I am successfully able to connect via ssms like so name, 41041. Maybe it is unable to connect because it is using name: 41041. Any ideas on how to fix this?

Resources