Cannot connect to SQL Server with Node.js and Tedious - javascript

When I try to use Node.js and Tedioius to connect to a local SQL Server instance I get this error:
{ [ConnectionError: Failed to connect to XXXXX:1433 - connect ECONNREFUSED]
name: 'ConnectionError',
message: 'Failed to connect to XXXXX:1433 - connect ECONNREFUSED',
code: 'ESOCKET' }
Here is my connection object:
var config = {
userName: 'username',
password: 'password',
server: 'XXXXX',
options: {
database: 'databasename',
instancename: 'SQLEXPRESS'
}
};
I have checked and TCP/IP is enabled and broadcasting on port 1443 according to Configuration Manager. The SQL Server Browser service is also running, which I read may be causing this type of issue if not. I have disabled my antivirus and firewall and that hasn't helped either.
Any insight?

So what I am guessing happens is that even though Tedious lets you include instance name in 'options' it either doesn't use it or can't use it as it needs to be used. After doing some research, what should be happening is when you give SQL Server the instance name, it redirects you from port 1433 to the dynamic port it is using for that instance. I didn't know it was using a dynamic port, but if your instance is named the port will always be dynamic. I don't know where I saw it broadcasting on 1433, that was my mistake.
To check the dynamic port, look here:
From this information, I changed my code to this:
var config = {
userName: 'username',
password: 'password',
server: 'XXXXX',
options: {
port: 49175,
database: 'databasename',
instancename: 'SQLEXPRESS'
}
};
All is good now, hope this helps someone.

If anyone else is new to SQL Server like I am, and is dealing with this issue, once you enable TCP/IP in SQL Server Config Manager by following these steps:
> SQL Server Network Config
> Protocols for YOURSQLSERVERINSTANCE
> TCP/IP
> Enable
you get a warning message that looks like this:
Any changes made will be saved; however, they will not take effect until the service is stopped and restarted.
I took this to mean, disconnect from the database service in SQL Server Management Studio and reconnect, but this needs to happen in SQL Server Config Manager under the SQL Server Services tab. Find you SQL Server instance, stop and restart it, and hopefully you will be golden! This worked like a charm for me. Oddly, enabling the Named Pipes protocol seemed to work without a restart (I could see the difference in the error message), so I thought for sure it had stopped and restarted as needed.
Also, be sure to enable SQL Server Browser services as well. This and enabling TCP/IP and restarting the service were the keys for me.

If you still have problems after enabling TCP/IP protocol, I would suggest you check that SQL Server Browser Service is running. In my case I spent a lot of time till I realised it wasn't running.
This configuration run fine for me:
var config = {
user: 'user',
password: 'userPwd',
server: 'localhost',
database: 'myDatabase',
options: {
truestedConnection: true,
instanceName: 'SQLEXPRESS'
}

If you still got this error,
"...'Failed to connect to Server:1433 - connect ECONNREFUSED Server IP:1433',
code: 'ESOCKET' }"
and you've checked all the following:
Enable TCP/IP
Open Port 1433
Config setup correctly (database, server, username and password}
No Dynamic ports configured
Check your SQL server version. In my case, I discovered that I could connect to SQL 2012, but not SQL server 2016 with the same code. It appears SQL Server 2016 is not supported by the tedious driver yet.

...
You have to enabled tcp/ip on protocol for MSSQLSERVER
and activate both authentication

here is the complete code
const {
Request
} = require('tedious');
var Connection = require('tedious').Connection;
var config = {
server: 'DESKTOP-RU9C12L', //update me
authentication: {
type: 'default',
options: {
userName: 'begaak', //update me
password: 'begaak#123', //update me
}
},
options: {
encrypt: true,
enableArithAbort: true,
integratedSecurity: true,
trustServerCertificate: true,
rowCollectionOnDone: true,
database: 'selvapoc' //update me
}
};
var connection = new Connection(config);
connection.connect(function(err) {
console.log('testing')
// var request = new Request("Select * from products", function(err, rowCount, rows) {
// console.log(rowCount);
// console.log(JSON.stringify(rows))
// });
// connection.execSql(request);
connection.execSql(new Request('SELECT * FROM Products', function(err, rowCount, rows) {
if (err) {
throw err;
}
})
.on('doneInProc', function(rowCount, more, rows) {
console.log(more, rows[0], rowCount); // not empty
}));
});
connection.on('connect', function(err) {
// If no error, then good to proceed.
if (err) console.log(err)
console.log("Connected");
});
before starting the code configure these with SQL SERVER CONFIGURATION MANAGER

Related

Whenever I tried to connect nodejs with sql sever getting error as 'Failed to connect to localhost'

I have created an nodejs application where I am trying to connect to sql server. But I am getting Failed to connect to localhost error
I have enabled TCP/IP connection in Sql server configuration manager.
Also started all services of Sql server. Still not able to connect.
ServiceEnabled Image
TCP/IP enabled image
Error Image
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var sql = require("mssql");
var config = {
user: 'sa',
password: 'password',
server: 'localhost',
database: 'testdb'
};
sql.connect(config, function (err) {
if (err) console.log(err);
var request = new sql.Request();
request.query('select * from persons', function (err, recordset) {
if (err) console.log(err)
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
Getting Failed to connect to localhost error.
After some search and youtube videos got to know that I haven't restarted my services.
Watched this video for database connections.
Steps for restarting services (for windows 10):
Press Window search key.
Type Services.msc and enter.
You will get screen like this.
Make Sure that SQL Server Agent, SQL Server Browser and SQL Server instance that you are using must be start and in running mode. (You can start/stop service from left pane as I have marked in Red on screenshot).
Try Connecting DB with Nodejs.
Happy Coding!!

Cannot Connect to SQL Server after hosting the app on heroku

I'm using mssql along with node.
I call a function to connect to the database:
const sql = require('mssql')
async () => {
try {
const pool = await sql.connect(`mssql://${process.env.DATAUSER}:${process.env.DATAPASS}#${process.env.SERVER}`)
} catch(err) {
console.log(err)
}
}
This works perfectly fine when i'm on a localhost but after i've hosted it to heroku and add the env variables. The error I get is (I changed the ip address to 5's):
ConnectionError: Failed to connect to 55.5.5.555:1433 in 15000ms
My process.env.SERVER = 55.5.5.555/SpecificDatabase and If that means anything
I don't see any reference to your specific database or schema in this code. It may be possible that your local implementation of the data server differs from the heroku implementation in respect to the default schema or database to which a user is directed. Therefore, you may need to add a database or schema field to your connection call.
For example, my pool code to connect to the OSU server is:
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host : 'classmysql.engr.oregonstate.edu',
user : 'username',
password : 'password',
database : 'database_name',
multipleStatements: true
});
module.exports.pool = pool;
Though my implementation here was with mysql and not mssql, it may hold true that you need to explicitly name a specific database or schema.

Trying to connect to a MySQL database using Node.js and the mysql javascript client

So i have been trying to connect to a MySQL database from my electron app:
<script>
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '*********',
user : '******',
password : '******',
port : '******',
debug : 'true'
});
console.log('trying to connect to DB')
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
connection.end()
</script>
My code gets stuck on connection.connect and after about 1 min it give me:
error connecting: Error: read ECONNRESET
at exports._errnoException (util.js:1024:11)
at TCP.onread (net.js:610:25)
I have no idea what to do, anyone have any ideas?
The chances are that your mssql instance on your lan is not configured to allow connections to anything but your local machine, i.e the machine that mssql is installed.
To allow connections from your LAN you need to edit the following:
edit my.conf and find the bind-address parameter in the [mysqld] section, this will probably be set to localhost or 127.0.0.1, you can either change this to the ip of the machine you want to connect to the database, or use a wildcard and allow your whole local range, e.g 192.168.0.* or 0.0.0.0
You will need to grant access to the database you are trying to connect to
GRANT ALL ON <local database name>.* TO <user>#<iptryingtoconnectfrom> IDENTIFIED BY '<database user password>';
Restart the mysql service and you should be good to go.

breeze-sequelize with MSSQL possible?

Is it currently possible to connect breeze-sequelize with a MS SQL server?
According to the doc of Sequelize, Sequelize does support MSSQL Server.
Though in the breeze doc there is no MS SQL server listed.
I am a bit confused now. And if it is not possible, is the breeze dev team planning to impl that? Or are there alternatives to use breeze in nodejs with an MSSQL server?
Yes it is actually possible. It took quite some time since the breeze-sequelize documentation is not very "newb friendly".
Here is my configuration for the MS SQL server. The tempHire example from the breeze samples on github was helping out a lot.
var dbConfig = {
user: 'username',
password: 'secret',
dbName: 'myDatabase'
};
var sequelizeOptions = {
host: 'hostname',
dialect: 'mssql',
port: 1433
};
function createSequelizeManager() {
var metadata = readMetadata();
var sm = new SequelizeManager(dbConfig, sequelizeOptions);
sm.importMetadata(metadata);
return sm;
}
The only thing i could not figure out until now is how to communicate with a specific MS SQL instance on a host e.g. localhost\MY_MSSQL_INSTANCE.
UPDATE
I actually did find out how to connect to a specific named instance.
So if you want to connect to an mssql instance like localhost\MY_MSSQL_INSTANCE, the sequelizeOptions should look like the following:
var sequelizeOptions = {
host: 'localhost',
dialect: 'mssql',
dialectOptions: {
instanceName: 'MY_MSSQL_INSTANCE'
}
};

My node.js https client always works regardless of certificate validity

This test program connects to an https server and gets some content. I've checked my server in browsers and with curl and the certificate is working correctly. If I run curl to grab data from the server it correctly complains about the certificate being unknown unless I pass it in with --cacert or turn security off with -k.
So the problem I am having is that although I think my client should be doing certificate authentication and I am telling it where the public certificate is, it just always works. If I remove the ca: option so it has no idea what the certificate is from the server then it silently works. I would like to catch the authentication error but I can't seem to do so.
var https = require('https');
var fs = require('fs');
function main() {
var data = '';
var get = https.get({
path: '/',
host: 'localhost',
port: 8000,
agent: false,
ca: [ fs.readFileSync('https_simple/cacert.pem') ]
}, function(x) {
x.setEncoding('utf8');
x.on('data', function(c) {data += c});
x.on('error', function(e) {
throw e;
});
x.on('end', function() {
console.log('Hai!. Here is the response:');
console.log(data);
});
});
get.on('error', function(e) {throw e});
get.end();
}
main();
In order to make this work I needed to upgrade to v0.7.8 (although any v0.7 should be fine) where the rejectUnauthorized functionality has been added to https.get
This combination of options is needed:
agent: false, // or you can supply your own agent, but if you don't you must set to false
rejectUnauthorized: true,
ca: [ fs.readFileSync('https_simple/cacert.pem') ]
Now if the authentication fails you will get an 'error' event and the request will not go ahead.
See the https.request documentation for details on making your own Agent
The bug fix was committed in this change: https://github.com/joyent/node/commit/f8c335d0
As per the documentation for https.request, the ca option of both https.get and https.request is an option from tls.connect. The documentation for the options to the tls.connect module function states:
ca: An array of strings or Buffers of trusted certificates. If this is
omitted several well known "root" CAs will be used, like VeriSign.
These are used to authorize connections.
Digging into the node.js source, the root certs used can be found here: https://github.com/joyent/node/blob/master/src/node_root_certs.h
So in short, with no authority cert provided as an option to https.get the tls module will attempt to authenticate the connection using the list of root certs anyway.
I do this in npm, using the request module. It goes like this:
var cacert = ... // in npm, this is a config setting
var request = require("request")
request.get({ url: "https://...",
ca: cacert,
strictSSL: true })
.on("response", function (resp) { ... })
.on("error", function (er) { ... })
The error event will be raised if the ssl isn't valid.
In V 0.6.15 you need to explicitly check whether or not the certificate validation passed or failed.
if (x.connection.authorized === false) {
console.log('SSL Authentication failed');
} else if (x.connection.authorized === true) {
console.log('SSL Authentication succeeded');
}

Categories