Node error connecting to SQL Server 2019 won't go away - node.js

i'm having some trouble connecting node to the database, it keeps throwing me an error of ssl and i tried a lot of different videos and stuff to see if it works but nothing does, here is what i'm currently doing
import sql from 'mssql'
const dbSettings = {
user: 'admin',
password: 'system',
server: 'localhost',
database: 'master',
options: {
trustedConnection: true,
encrypt: true,
trustServerCertificate: true,
},
}
async function getConnection() {
const pool = sql.connect(dbSettings)
const result = await sql.query("SELECT 1")
console.log(result)
}
getConnection()
i also tried this as well but didn't work either
async function getConnection() {
const pool = await sql.connect(dbSettings)
const result = await pool.request().query("SELECT 1")
console.log(result)
i also checked if the SQL Server authentication is enabled with windows and SQL Server and it is, i can log in into SQL Server with that info, but somehow is having trouble creating the connection, by the way, this is the error message it is showing me:
node_modules\mssql\lib\tedious\connection-pool.js:70
err = new ConnectionError(err)
^
ConnectionError: Failed to connect to localhost:1433 - 186B0000:error:0A000102:SSL routines:ssl_choose_client_version:unsupported protocol:c:\ws\deps\openssl\openssl\ssl\statem\statem_lib.c:1986
any tips or solution you can give me to solve this problem would be really helpful to me, thank you very much in advance.
EDIT
I noticed that the connection error only appears when i call the function getConnection if i remove it it doesn't appear, however i need to make sure that the connection was properly established and see the response from the database to move on

change encrypt: true to encrypt: false

Related

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 connect to SQL Server with Windows authentication from Node.JS using knex module

I am trying to connect SQL Server using knex with Windows Authentication from my node.js application.
Config:
{
client: 'mssql',
connection: {
database: 'MyDBName',
host: 'xx.xx.xx.xxx',
server: 'MY-SERVER_NAME\\SQLEXPRESS',
options: {
encrypt: false,
trustedConnection: true,
},
},
}
I didn't add username and password in the config as I have added trustedConnection: true for Windows Authentication.
But I am getting the following error:
Login failed for user ''.
Even if I add add username and password, I get the same error.
Any suggestion will be of great help. Thanks
knex uses mssql which in turn uses either tedious or msnodesqlv8. tedious doesn't support Windows Authentication. The default is tedious. Trying to use tedious with Windows Authentication results in ... Login failed for user ''.. The full error message is :
(node:16568) UnhandledPromiseRejectionWarning: ConnectionError: Login failed for user ''.
at Connection.<anonymous> (K:\testprojects\nodesql\node_modules\mssql\lib\tedious.js:244:17)
at Object.onceWrapper (events.js:291:20)
at Connection.emit (events.js:203:13)
at Connection.processLogin7Response (K:\testprojects\nodesql\node_modules\mssql\node_modules\tedious\lib\connection.js:1397:14)
at Connection.message (K:\testprojects\nodesql\node_modules\mssql\node_modules\tedious\lib\connection.js:1932:14)
at Connection.dispatchEvent (K:\testprojects\nodesql\node_modules\mssql\node_modules\tedious\lib\connection.js:1084:36)
at MessageIO.<anonymous> (K:\testprojects\nodesql\node_modules\mssql\node_modules\tedious\lib\connection.js:984:14)
at MessageIO.emit (events.js:203:13)
at Message.<anonymous> (K:\testprojects\nodesql\node_modules\mssql\node_modules\tedious\lib\message-io.js:32:14)
at Message.emit (events.js:208:15)
Which clearly shows that the source is tedious.
To get this I used this snippet :
const sql = require("mssql");
const config = {
database: "Master",
server: "myserver",
options: {
trustedConnection: true
}
};
(async () => {
await sql.connect(config)
const result = await sql.query`select name from sys.databases`
console.dir(result)
})()
The docs explain that you need to use const sql = require("mssql/msnodesqlv8"); to use msnodesqlv8, eg :
const sql = require("mssql");
const config = {
database: "Master",
server: "myserver",
options: {
trustedConnection: true
}
};
After this change the query runs and produces a list of database names
Unfortunately, this won't help with knex, as it loads and uses tedious directly. Despite what the code comment says, msnodesqlv8 is actively maintained and had a release only 4 days ago.
I was able to connect using msnodeqlv8 by making a new dialect based on this example
I just added the msnodesqlv8 module and used the following code, hopefully it helps someone out:
require('mssql/msnodesqlv8');
let Knex = require("knex");
let Dialect = require(`knex/lib/dialects/mssql/index.js`);
Dialect.prototype._driver = () => require('mssql/msnodesqlv8');
let sql = Knex({
client: Dialect,
connection: {
server: "<sql server>",
port: 1433,
database: "<database name>",
driver: "msnodesqlv8",
options: {
trustedConnection: true
}
}
});
Thanks

How to perform an update using mssql node module and close the connection properly

const sql = require('mssql');
var dbConfig = {
server: "localhost",
database: "veiculos",
user: "guest2",
password: "mypassword",
port: 1433,
debug: true,
encrypt: true
};
sql.connect(dbConfig);
const request = new sql.Request()
request.query('update producao.carros set gostar += 1 where carroid = 37', (err, result) => {
console.log(result)
})
When I run this code I get
"tedious deprecated The default value for options.encrypt will change from false to true. Please pass false explicitly if you want to retain current behaviour. node_modules/mssql/lib/tedious.js:230:23"
and the record is not updated.
When I try to run twice, I get this:
if (globalConnection) throw new Error('Global connection already exists. Call sql.close() first.')
Error: Global connection already exists. Call sql.close() first.
and the record is not updated and an exception stops the server.
The last error is clear, but why my record is not updated?
close the sql connection after updating
use sql.close()
this will close Global connection and make it available for second request

NodeJS Connecting to SQL Server Port Not Found error

I'm trying to connect to SQL Server:
var sql = require("mssql");
var dbConfig = {
server: "LAP12\\INSTANCE1",
database: "SampleDb",
port: 1433,
options: {
trustedConnection: true
}
};
// connect to your database
sql.connect(dbConfig, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from SampleTable', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
But I receive this error:
ConnectionError: Port for INSTANCE1 not found in ServerName...
I've tried to follow instructions here https://github.com/patriksimek/node-mssql/issues/130 , but that didn't help. TCP is enabled.
Changing config to this didn't help either:
var dbConfig = {
server: "LAP12",
port: 1433,
options: {
instanceName: 'INSTANCE1',
database: 'SampleDb',
trustedConnection: true,
}
};
Ok, I had the same issue, will try to help.
this is my config exemple
const config = {
user: 'sa',
password: '****',
server: 'DESKTOP-Q5TO47P',
database: 'dbname',
options: {
encrypt: false
}
};
You need to turn on the SQL Server Browser. Go to start up menu or the search and look for SQL Server Configuration Manager. Run it! (Im using 2018 version)
In the left Tab click on SQL Server Services
now in the right tab double click on SQL Server Browser
will open a window, you will see 3 tabs, go for the Service tab
change start mode to Automatic and apply
left click on SQL Server Browser and click restart
Back to the right tab click on SQL Server Network Configuration
then Client Protocols
change TCP/IP to enable
Let me know if it works.
after adding this encrypt: false, application not showing any error neither responding, Its not connecting to DB
In my case the "SQL Browser" is not reachable because the firewall port is not open.
Solution for me is to open the port or change dbConfig to (no instance name, no port):
var dbConfig = {
server: "LAP12",
database: "SampleDb",
options: {
trustedConnection: true
}
};
The port is still closed to SQL-Browser, with that change I can connect to my DB.
My nodejs Package 'mssql'

Mongoose fails to reconnect after replicaset not found error

I'm running a small website that connects to MongoDB Atlas. It has a replicaset with 3 members. For the most part, everything works just fine, but every now an then Atlas' replicaset crashes (or something?) and Mongoose stops working from then on. It throws a single error - MongoError: no primary found in replicaset and that's it.
It doesn't fire mongoose.connection.on('error'), and no errors are reported after this point. It just fails to return any data.
It's sort of hard for me to debug this, as this is running in production, and I have no way of telling when replicaset will fail. Here's how I connect:
function connect() {
tries++;
mongoose.Promise = Promise;
const { uri, options } = config.mongoDb;
return mongoose.connect(uri, options);
}
let db = connect();
db
.connection
.on('error', (err) => {
Raven.captureException(err);
db.disconnect();
})
.on('disconnected', () => {
db = connect();
});
And my options look like this:
options: {
server: {
autoReconnect: true,
ssl: true,
poolSize: 10,
socket_option: {
keepAlive: true
}
}
}
Has anyone had similar problems before? Any idea what I'm doing wrong here, or how to actually catch the error, so I can properly reconnect?

Resources