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.
Related
So I have this piece of code that is responsible for checking if a connection is valid:
const sequelize = new Sequelize(req.body.database, req.body.user, req.body.password, {
host: req.body.host,
dialect: 'mssql',
port: req.body.port,
dialectOptions: {
options: {
encrypt: true,
}
}
});
sequelize.authenticate().then((err) => {
res.send('Connected');
})
.catch((err) => {
console.log(err.message)
res.send(err.message);
});
This worked perfectly when I was connecting to a local DB on my network. However, when I was trying to connect to a DB through a VPN (simulating a local network) I got the following error:
Failed to connect to 10.1.90.20:1433 - 4C300000:error:0A000102:SSL
routines:ssl_choose_client_version:unsupported
protocol:c:\ws\deps\openssl\openssl\ssl\statem\statem_lib.c:1983:
I read somewhere that adding
cryptoCredentialsDetails: {
minVersion: 'TLSv1'
}
in the options will resolve this but it just gave me a new error:
Failed to connect to 10.1.90.20:1433 - 70290000:error:0A0C0103:SSL
routines:tls_process_key_exchange:internal
error:c:\ws\deps\openssl\openssl\ssl\statem\statem_clnt.c:2255:
Any idea how to fix this?
Keep in mind that both Databases are local however one of them is on a remote network accessible through SSL VPN.
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
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,
}
};
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/
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;