Connecting to SQL server through Node.js - 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?

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

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,
}
};

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
}

Connection fail to SQL Server using NodeJS mssql msnodesqlv8 from the server

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

My Node.js local application won't connect to Azure SQL DB

I am developing a Node.js-Express-EJS web application, with Azure SQL DB (cloud version of MS SQL Server).
I try to test my connection first on the remote Azure SQL DB, using SQL Server Management Studio. First, I set my machine's IP to be allowed in Azure SQL DB firewall rules. Then I was able to get into the database, create and populate table, and query using the Management Studio.
Now, I have the Node.js app locally first. However, it seems it can't connect to the remote Azure SQL DB using same credentials.
First, I use the tutorial in node-mssql:
/* Using node-mssql */
var sql = require('mssql');
router.get('/test/mssql', function(req, res, next) {
console.log('Testing node-mssql')
sql.connect("mssql://<username>:<password>#<server>.database.windows.net/<db>")
.then(function() {
new sql.Request()
.query('SELECT * FROM mytable')
.then(function(recordset) {
console.dir(recordset);
}).catch(function(err) {
console.log(err);
});
}).catch(function(err) {
console.log(err);
});
});
I was only able to get from the console
'Testing node-mssql'
GET /contact/test/mssql - - ms - -
But no response, it seems its waiting forever, it didn't even throw error.
Same thing happens when I use Sequelize.js
/* Using Sequelize.js */
var Sequelize = require('sequelize');
var sequelize = new Sequelize('<db>', '<username>', '<password>', {
host: '<mydb>.database.windows.net',
dialect: 'mssql',
pool: {
max: 5,
min: 0,
idle: 10000
},
});
router.get('/test/sequelize', function(req, res, next) {
console.log('Testing sequelize');
sequelize.authenticate()
.then(function(err) {
console.log('Connection has been established successfully');
})
.catch(function(err) {
console.log('Unable to connect to the database:', err);
});
});
Result:
Testing sequelize
GET /test/sequelize - - ms - -
Here are the versions that I am using:
Node.js - 4.6.0
express - 4.14.0
mssql - 3.3.0
sequelize - 3.30.2
tedious - 1.14.0
(I wonder if this has to do with me connected on WiFi? But impossible, bec. Management Studio works fine right?)
If you're trying it out with Azure SQL Database, you'd need to add ?encrypt=true to your connection string that will look like:
mssql://<username>:<password>#<server>.database.windows.net/<db>?encrypt=true
For Sequelize.js, you'd need this: dialectOptions: { encrypt: true }. The code will look like:
var sequelize = new Sequelize('<db>', '<username>', '<password>', {
host: '<mydb>.database.windows.net',
dialect: 'mssql',
// Use this if you're on Windows Azure
dialectOptions: {
encrypt: true
},
pool: {
max: 5,
min: 0,
idle: 10000
},
});
I think the issue is with your connection string, as that doesn't look like a SQL Database connection string that would work.
For mssql, try connecting like this:
var config = {
server: "<servername>.database.windows.net",
database: "<dbname>",
user: "<username>",
password: "<password>",
port: 1433,
options: {
encrypt: true
}
};
sql.connect(config).then(function() { ... } )
FYI for reference, SQL Database (at least through .net) expects a connection string like this, so you might have success with a similar connection string directly passed to sql.connect() (though I haven't tried it):
Server=tcp:[serverName].database.windows.net;Database=myDataBase;
User ID=[LoginForDb]#[serverName];Password=myPassword;Trusted_Connection=False;
Encrypt=True;

Resources