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

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;

Related

Node.js and mssql connection

I created this Microsoft SQL Server and a database with two tables in it. I am using Node.js for the backend but I am having trouble making a connection from node.js to mssql. I am using Visual Studio and have all the required frameworks and packages needed. I am not getting any errors but I'm also not getting the output. I want to understand if its connected and I want the code to work. My node.js and SQL are working fine though.
const sql = require('mssql')
const sqlConfig = {
server: "10.0.0.102\\MSSQLSERVER",
port: 1433,
pool: {
max: 10,
min: 0,
idleTimeoutMillis: 30000
},
options: {
encrypt: true,
trustServerCertificate: false
}
}
async () => {
try {
// make sure that any items are correctly URL encoded in the connection string
await sql.connect(sqlConfig)
const result = await sql.query`select * from multiuserlogin`
console.dir(result)
} catch (err) {
// ... error checks
}
}

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

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/

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
}

Unable to use tedious with Azure database

I've a node application which do have a connection to SQL Server.
Also, I'm using database as a service from Azure.
Code Snippet :
import { Connection } from 'tedious';
import { Request } from 'tedious';
var config = {
userName: 'dbuser',
password: 'dbpassword',
server: 'mydatabase.database.windows.net',
options: {
instanceName: 'SQLEXPRESS', // Removed this line while deploying it on server as it has no instance.
database: 'dbname'
}
};
connection = new Connection(config);
connection.on('connect', function(err) {
if (err) {
console.log('error : '+err);
} else {
console.log("Connected to Database");
}
});
It has a successful connection, if done, locally.
Console Output => Connected to Database.
Deep dive done using console log :
-> Connection object is being created, but, the event ".on" is not being able to establish.
-> The connection gets established when deployed locally, while, when deployed on server, it doesn't works.
Based on the documentation here, you need to provide an additional option for encrypted connection.
Please try the following for config:
var config = {
userName: 'dbuser',
password: 'dbpassword',
server: 'mydatabase.database.windows.net',
options: {
database: 'dbname',
encrypt: true //Need to add this for connecting to Azure DB
}
};
Using this configuration, I was able to connect to my database hosted in Azure.

Resources