Node.js Connection with SQL Server windows authentication - sql-server
I'm trying to connect node.js to mssql in Windows Authentication mode. I installed the tedious,mssql and msnodesqlv8 modules, but I still can't figure out how to open a connection.
This is what I tried:
var sql = require('mssql');
var config = {
driver: 'msnodesqlv8',
server: 'POPPY-GI\\SQLEXPRESS',
database: 'NodinSports',
options:{
trustedConnection: true,
useUTC: true}}
sql.connect(config).then(function() {
new sql.Request().query('select * from users')
.then(function(recordset){
console.log(recordset);
}).catch(function(err) {
console.log(err);});
}).catch(function(err) {
console.log(err);});
After running I get a long error saying:
`ConnectionError`: Port for `SQLEXPRESS` not found in
`ServerName`;POPPYGI;`InstanceName;SQLEXPRESS;IsClustered`;No;Version;12.0.2000.8;;
at Connection.tedious.once.err (D:\Never Lazy\University\`AN2, SEM 2\WEB\`Projek`\node_modules\`mssql`\lib\`tedious.js:216:17`)
at Connection.g (events.js:291:16)
at emitOne (events.js:96:13)
at Connection.emit (events.js:188:7)
at D:\Never Lazy\University\AN2,SEM2\WEB\Projekt\node_modules\tedious\lib\connection.js:570:27
at D:\Never Lazy\University\AN2,SEM2\WEB\Projekt\node_modules\tedious\lib\instance-lookup.js:91:24
at Socket.onMessage (D:\Never Lazy\University\AN2,SEM2\WEB\Projekt\node_modules\tedious\lib\sender.js:140:9)
at emitTwo (events.js:106:13)
at Socket.emit (events.js:191:7)
at UDP.onMessage (dgram.js:549:8)
code: 'EINSTLOOKUP',
I would be really thankful for any help.
FIXED:
In services.msc check if the followings are enabled:
SQL Server(*server_name*) -- in my case `SQLEXPRESS`
SQL Server Browser
SQL Server Agent(*server_name*) -- if you are using `SQLEXPRESS` this doesn't need to run
In SQL Server Configuration Manager -> Protocols for server_name: enable TCP/IP.
To make sure everything will be fine, check the port the server is using (SQL Server Configuration Manager -> SQL Native Client Configuration -> Client Protocols -> double click on TCP/IP -> Default Port ) , and add the port: *your_port* to the code in var config = { ... }.
Lastly, change var sql = require('mssql'); to var sql = require("mssql/msnodesqlv8");
Install the following modules:
"dependencies": {
"msnodesqlv8": "^0.4.14",
"mssql": "^4.1.0"
}
My node version: v8.1.4
const sql = require("mssql/msnodesqlv8");
const main = async () => {
const pool = new sql.ConnectionPool({
server: "myservername",
database: "mydbname",
options: {
trustedConnection: true
}
});
await pool.connect();
const request = new sql.Request(pool);
const query = `SELECT [FirstName]
,[LastName]
,[Email]
FROM [Dev].[Users]`;
const result = await request.query(query);
console.dir(result);
};
main();
(You can do it without async or older versions: https://stackoverflow.com/a/40406998/639575)
The solution given by beatoss works for windows but not for Linux/mac. The msnodesqlv8 driver only works for Windows. For Linux/mac environment, try odbc instead.
It may be too late to answer, but this recently happened with me and it drove me crazy!!! I was trying to connect my db to express and I was working with windows authentication mode. For two long days I kept googling and refreshing until I got this article: https://www.liquidweb.com/kb/troubleshooting-microsoft-sql-server-error-18456-login-failed-user/
So in a nutshell;
First I installed the msnodesqlv8 driver for windows authentication, then in the my server on ssms, I right clicked on my server then in properties and then security, I enabled sql server and windows authentication mode, then in the object explorer, clicked on the plus next to the server, then security, then logins. There I saw sa with a cross next to it. In it's properties, I changed my password to something easier to remember (optional), then in the status, set the login to enable. PHEW!
Now my config code: <br / >
const config = {
user: 'sa',
password: '123',
driver: "msnodesqlv8",
server: 'UZAIR-S_PC\\SQLEXPRESS',
database: 'LearningExpressJS',
options: {
trustedconnection: true,
enableArithAbort : true,
trustServerCertificate: true,
instancename : 'SQLEXPRESS'
},
port: 58018
}
This works finally !!!!!!!!!!!!!!!
Related
Failed to connect to local SQL Server using node
I am trying to connect to a local SQL Server database using the following config: var config = { server: "localhost", port:1433, user: 'sa', password: 'sa', database: 'newarbete', options: { trustedconnection:true, } } but I failed. I get this error Failed to connect to localhost:1433 - Could not connect (sequence) I can connect to the same db when it is on the server (changing the config parameters of course). What is wrong with the config parameters for the local database, or what I should do to make work here?
Config entry in node.js in case if of windows authentication to connect to SQL Server
How to create config entry in Node.Js to connect to SQL Server in the case of Windows Authentication using only mssql module? I'm using this approach: exports.dbConfig = { server: "AKASH", database: "SampleDB", port: 1433, options: { trustedConnection: true } };
Why can't I connect to a SQL database from Node.js application on Mac?
I guess my initial question is, is it possible to connect to a sql database using the npm mssql module from a node application on a mac? I figured the mssql module was just an alternative to tedious.js - am I wrong? Is it just for windows use? var db = require("mssql"); var config = { server: server, user: user, password: password, database: database }; var connection = new db.Connection(config); connection.connect(config, function(err) { if(err) { console.log("Error: " + err); } console.log("Success."); })
Unfortunately, I missed the docs recommendation to add encrypt: true to the config options if using Windows Azure. Added that and it worked fine. It wasn't giving me any error messages beforehand, so it took a while to figure out XD var config = { server: server, user: user, password: password, database: database, options: { encrypt: true // Use this if you're on Windows Azure } };
nodejs with mssql connection timeout error
I am writing a node.js console app for communicating with SQL Server 2008. var sql = require('mssql'); var connection = new sql.Connection({ user: 'sa', password: 'password', server: 'localhost\\SQLEXPRESS', database: 'Demo' }); connection.connect(function (err) { if (err) console.log(err); var request = new sql.Request(connection); // or: var request = connection1.request(); request.query('select * from EmpInfo', function (err, recordset) { // ... error checks console.dir(recordset); }) }); When I execute this code, a TIMEOUT error occurs.
1.you have to run "SQL Server Browser" service. 2.enable "TCP/IP" *you need restart "SQLEXPRESS" service it also helps bellow error. ConnectionError: Port for SQLEXPRESS not found in "ServerName"
Maybe your query takes too long. Try to do SELECT 1 a. If it works - change the timeout. Doc for requestTimeout:
Actually It was error from "Sql Server Configuration Manager". Tcp\Ip was disabled in Sql server network configuration.
Node.js MSSQL tedius ConnectionError: Failed to connect to localhost:1433 - connect ECONNREFUSED
I am trying to connect to MSSQL 2012 using NodeJS with the mssql connection interface. When attempting to connect I get the following error: { [ConnectionError: Failed to connect to localhost:1433 - connect ECONNREFUSED] name: 'ConnectionError', message: 'Failed to conncet to localhost:1433 - connect ECONNREFUSED', code: 'ESOCKET' } Any ideas on how to fix this?
The solution is to enable TCP connections which are disabled by default.
My case wasn't exactly the same as Matt's, but his screenshot was enough to remember me what was missing. As it is said here, when you are using the SQL Server Instance Name to connect to it, you must have SQL Server Browser running. options.instanceName The instance name to connect to. The SQL Server Browser service must be running on the database server, and UDP port 1434 on the database server must be reachable. (no default) Mutually exclusive with options.port.
If after enabling the TCP connection and your configuration is still not working. Here's my own-configuration. var config = { "user": 'admin', "password": 'password', "server": 'WINDOWS-PC', "database": 'database_name', "port": 61427, // make sure to change port "dialect": "mssql", "dialectOptions": { "instanceName": "SQLEXPRESS" } };
If somebody still struggles to connect despite doing all that was proposed. In my case I had to manually set TCP Port property to 1433 in SQL Server Network Configuration -> Protocols for ... -> TCP/IP -> IP Addresses -> IPAll. [
Best practice is to first verify the connection to the SQL server using a query analyzer (SQL Management Studio (Windows) or SQLPro for MSSQL (Mac)) using the same protocol, port and credentials as you wish to use via your application. In Management Studio, the format is Server,Port (e.g. 192.168.1.10,1433); and you'll probably be using SQL Server Authentication instead of Windows Authentication. Steps to configure the SQL Server: Install with Mixed Authentication, if you intend to use SQL Server Authentication. Setup SQL Server to listen on TCP on a fixed port number: SQL Configuration Manager SQL Server Network Configuration Protocols for {Instance} TCP/IP - Enabled (double-click) IP Address (on all desired interfaces) TCP Dynamic Ports = BLANK! (not zero) TCP Port - 1433 (or desired port)
In my case there was a configuration issue.This was the wrong configuration let config = { server: 'localhost', authentication: { type: 'default', options: { userName: 'sa', // update me password: 'xxxxx' // update me } }, options: { database: 'SampleDB', validateBulkLoadParameters:false, }} Then I have added encrypt variable to the options.It solved my issue.Corrected configuration let config = { server: 'localhost', authentication: { type: 'default', options: { userName: 'sa', // update me password: 'xxxxxx' // update me } }, options: { database: 'SampleDB', validateBulkLoadParameters:false, encrypt: false, } }
**Please follow the connection configuration and little test:** //Declare global variable var http = require('http'); var events = require('events'); var nodemailer = require('nodemailer'); var sql = require('mssql');<br/> var Request = require('tedious').Request; var TYPES = require('tedious').TYPES; //Create an http server http.createServer(function(req,res) { res.writeHead(200, {'Content-Type': 'text/html'}); var Connection = require('tedious').Connection; //Configure the connection var config = { userName: '<user id>', password: '<password>', server: '<system ip>', options: {database: '<database name>'} }; var connection = new Connection(config); connection.on('connect', function(err) { console.log("Connected"); executeStatement(); }); function executeStatement() { request = new Request("select getdate();", function(err) { if (err) { console.log(err);} }); var result = ""; request.on('row', function(columns) { columns.forEach(function(column) { if (column.value === null) { console.log('NULL'); } else { result+= column.value + " "; } }); console.log(result); result =""; }); connection.execSql(request); }; return res.end(); }).listen(8080); //Post configuration test on browser: http://localhost:8080/
Apart from setting TCP port no to 1433. If you are getting "Connection lost - Cannot call write after a stream was destroyed" error This error will also come if you use options.encrypt: true on Node v12+ with old SQL Server versions. This is caused by Node v12 requiring TLS 1.2. install the TLS 1.2 security patch for your SQL Server run node with backwards compatibility flag: node --tls-min-v1.0 eg: node --tls-min-v1.0 app.js disable encrypted communication by setting options.encrypt: false (optional) Config Object: const config = { user: '...', password: '...', server: 'localhost', database: '...', 'options.encrypt': false } Ref: https://github.com/tediousjs/tedious/issues/903#issuecomment-614597523
I couldn't connect with 'localhost' although I use 'localhost' in SQL Management Studio and other applications. When I used Computer Name (network address), it worked!
My issue was that I needed to start sqlserver using docker first on my mac using this command sudo docker start sqlserver
For me changing this condition from 'No' to 'Yes' worked: switch (key) { case 'instance': return this.config.options.instanceName case 'trusted': return this.config.options.trustedConnection ? 'Yes' : 'Yes' It just doesn't load the value from the options object even if I provide it. I hardcoded this change in file \node_modules\mssql\lib\msnodesqlv8\connection-pool.js