Node.JS can't connect a local SQL Server - sql-server

I'm trying to pass my windows domain credentials to a LOCAL SQL Server and I'm getting this weird error:
Could not connect to sql: { [ConnectionError: Login failed. The login is from a
n untrusted domain and cannot be used with Windows authentication.]
name: 'ConnectionError',
message: 'Login failed. The login is from an untrusted domain and cannot be us
ed with Windows authentication.',
code: 'ELOGIN' }
I also tried connecting to a remote SQL Server without success.
When I pass SQL Authentication it works fine
Here's the code:
var sql = require('mssql');
var conn_str = {
server: 'ccc',
database: 'TEST',
domain: 'Name',
user: 'xxxxx',
password: 'xx',
options : {
trustedConnection : true
}
}
var connection = new sql.Connection(conn_str, function(err) {
// ... error checks
if(err) {
return console.log("Could not connect to sql: ", err);
}
// Query
var request = new sql.Request(connection);
request.query('select top 10 * from xxxx (nolock)', function(err,recordset) {
// ... error checks
console.dir(recordset);
});
// Stored Procedure
});

Related

'Login failed for user' error when using SQL Server, but not when using tedious

I'm trying to connect to a SQL Server Express database setup on a Windows 10 machine in network from a macbook running the following code. I can connect using tedious, but not using mssql. It's as if the username or password is wrong. The reason I want to get mssql working is for the pooling and because it appears to have more support... otherwise I would just use tedious. The code is creating both connections and the output shows tedious connecting but mssql fails.
const express = require('express');
const sql = require('mssql');
const bodyParser = require('body-parser');
const app = express();
var Connection = require('tedious').Connection;
// Body Parser Middleware
app.use(bodyParser.json());
// CORS Middleware
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// define listineng port
const PORT = 5006;
// define tedious config
var config = {
server: "JAMBER-VR1.local",
userName: "testuser",
password: "testuserpass",
database: "SQLEXPRESS",
options: {
encrypt: false
}
};
var connection = new Connection (config);
connection.on('connect', function(err){
if(err!=null){
console.log(err);
console.log("not connected - tedious");
}
else{
console.log("Connected - tedious")
connection.close();
};
});
// Define SQL config
const dbConfig = {
user: 'testuser',
password: 'testuserpass',
server: 'JAMBER-VR1.local',
database: 'SQLEXPRESS',
// port: 1433,
// logging: true,
options: {encrypt: false},
pool: {
max: 100,
min: 0,
idleTimeoutMillis: 30000
}
}
const executeQuery = async () => {
try {
let pool = await sql.connect(dbConfig);
console.log("pool connected - mssql");
let result = await pool.request()
.input('input_parameter', sql.Int, value)
.query('select * from donor')
console.log("Result: ", result);
} catch (err) {
console.log("Error: ", err);
}
}
executeQuery();
I'm getting the following error.
[nodemon] starting node index.js
Running on port 5006
Connected - tedious
Error: { ConnectionError: Login failed for user 'testuser'.
at Connection.tedious.once.err (/Users/jordanszymczyk/Code/TRTL/server_sql /node_modules/mssql/lib/tedious.js:237:17)
at Object.onceWrapper (events.js:273:13)
at Connection.emit (events.js:182:13)
at Connection.processLogin7Response (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/tedious/lib/connection.js:1292:16)
at Connection.message (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/tedious/lib/connection.js:1805:14)
at Connection.dispatchEvent (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/tedious/lib/connection.js:1004:38)
at MessageIO. (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/tedious/lib/connection.js:884:18)
at MessageIO.emit (events.js:182:13)
at ReadablePacketStream. (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/tedious/lib/message-io.js:104:16)
at ReadablePacketStream.emit (events.js:182:13)
code: 'ELOGIN',
originalError:
{ ConnectionError: Login failed for user 'testuser'.
at ConnectionError (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/tedious/lib/errors.js:12:12)
at Parser. (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/tedious/lib/connection.js:628:33)
at Parser.emit (events.js:182:13)
at Parser. (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/tedious/lib/token/token-stream-parser.js:54:15)
at Parser.emit (events.js:182:13)
at addChunk (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/readable-stream/lib/_stream_readable.js:291:12)
at readableAddChunk (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/readable-stream/lib/_stream_readable.js:278:11)
at Parser.Readable.push (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/readable-stream/lib/_stream_readable.js:245:10)
at Parser.Transform.push (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/readable-stream/lib/_stream_transform.js:148:32)
at doneParsing (/Users/jordanszymczyk/Code/TRTL/server_sql/node_modules/tedious/lib/token/stream-parser.js:110:18)
message: 'Login failed for user 'testuser'.',
code: 'ELOGIN' },
name: 'ConnectionError' }
You can see the console.log("Connected - tedious") prints, then the mssql error follows immediately.
I've also tried using the local IP with the same results.
Testing through sqlcmd works.
dont forget to active both authentication
SQLEXPRESS will be the name of your SQL Server Express server instance (ie- Server). I don't see it in your code, but I'm guessing the database name is not SQLEXPRESS?
In your mssql connection dbConfig try changing Database to the real name of the database you created on your SQL Express instance.
The fixed dgconfig is as follows:
const dbConfig = {
user: 'testuser',
password: 'testuserpass',
server: 'JAMBER-VR1.local',
database: 'donor',
options: {encrypt: false},
pool: {
max: 100,
min: 0,
idleTimeoutMillis: 30000
}
}
Removed SQLEXPRESS and replaced it with the database name.

Nodejs mssql ConnectionError: Login failed for user ' '

This is my code:
var sql = require("mssql");
var dbConfig = {
server: "server",
username: "user",
password: "password",
database: "database"
};
function getEmp() {
var conn = new sql.Connection(dbConfig);
console.log(conn);
var req = new sql.Request(conn);
conn.connect(function (err) {
if (err) {
console.log(err);
return;
}
req.query("SELECT * FROM Alg.User", function (err, recordset) {
if (err) {
console.log(err);
return;
}
else {
console.log(recordset);
}
conn.close();
});
});
}
getEmp();
And this is the error I'm logging:
{ ConnectionError: Login failed for user ''.
at Connection.<anonymous> (c:\users\milan\documents\visual studio 2015\Projects\SampleSQLConn\SampleSQLConn\node_modules\mssql\lib\tedious.js:378:25)
at Connection.g (events.js:291:16)
at emitOne (events.js:96:13)
at Connection.emit (events.js:188:7)
at Connection.processLogin7Response (c:\users\milan\documents\visual studio 2015\Projects\SampleSQLConn\SampleSQLConn\node_modules\tedious\lib\connection.js:672:16)
at Connection.message (c:\users\milan\documents\visual studio 2015\Projects\SampleSQLConn\SampleSQLConn\node_modules\tedious\lib\connection.js:1082:21)
at Connection.dispatchEvent (c:\users\milan\documents\visual studio 2015\Projects\SampleSQLConn\SampleSQLConn\node_modules\tedious\lib\connection.js:519:45)
at MessageIO.<anonymous> (c:\users\milan\documents\visual studio 2015\Projects\SampleSQLConn\SampleSQLConn\node_modules\tedious\lib\connection.js:439:23)
at emitNone (events.js:86:13)
at MessageIO.emit (events.js:185:7)
name: 'ConnectionError',
message: 'Login failed for user \'\'.',
code: 'ELOGIN' }
Anyone knows what I'm doing wrong? It looks like my variable username isn't put in the connectionstring? But I have no idea why...
Thanks in advance!
Solution:
The problem was that in dbConfig, the username variable should be changed to user! And the sql query was wrong also, it should have been [Alg].[User], because 'User' is a keyword!
Using tedious / msnodesqlv8 driver for Windows worked for me:
Instead of:
var sql = require("mssql");
I changed it to:
var sql = require("mssql/msnodesqlv8");
I did not hard code user name/password.
Here's what my dbconfig looks like:
var db_config = {
driver: "msnodesqlv8",
server: "ServerName",
database: "databaseName",
options: {
trustedConnection: true,
useUTC: true
}
}
Please make "username" to "user" in your configuration. If you try to console.log(conn), you will see that configuration is using "user" instead of userName.
I have answered this question, please refer to
SQL Server Error "[ConnectionError: Login failed for user '****'.] "while connecting SQL Server with Nodejs using MSSQL
For google viewers...
If the above solution doesn't work for you. You should check the SQL Server Browser in Computer services is running as this is what processes the requests to the server.
That one stumped me for a while
Change 'username' of dbConfig to 'user'
For me, connecting to an Azure SQL database, this was fixed by adding this to my mssql.config. I did not need to specify a particular driver, as #shahreen did
options: {
trustedConnection: true
}

Getting Logon failed for login 'sa' due to trigger execution. in nodejs app using mssql

I am trying to connect to a remote database using below code in node js and getting "Logon failed for login 'sa' due to trigger execution." error.
// Database connection
var sql = require('mssql');
// Change the config settings to match your
// SQL Server and database
var config = {
"server": "my database server IP", // 127.0.0.1
"user": "nodejs",
"password": "mypassword",
"database": "mydatabase"
};
sql.setDefaultConfig( config );
sql.execute( {
query: "SELECT * FROM INFORMATION_SCHEMA.TABLES"
} ).then( function( results ) {
console.log( results );
}, function( err ) {
console.log( "Something bad happened:", err );
}
);
The code is not connecting but when I provide my local IP (127.0.0.1), it works just fine.
FYI: my remote database is accessible if I connect it using SQL Server Management Studio.
Driver Reference: https://www.npmjs.com/package/mssql

How to connect to SQL Server with windows authentication from Node.JS using mssql module

Hi I'm unable to connect to SQL server that is using windows authentication in node js. I'm using the mssql module. The error message is :
[ConnectionError: Login failed for user ''. The user is not associated with a trusted SQL Server connection.]
name: 'ConnectionError',
message: 'Login failed for user \'\'. The user is not associated with a trusted SQL Server connection.',
code: 'ELOGIN' }
Here is my code:
config = {
server : "localhost\\MSSQLSERVER",
database : "mydatabase",
port : 1433
}
function loadDepts() {
var conn = new sql.Connection(config);
var request = sql.Request(conn);
conn.connect(function(err) {
if (err) {
console.log(err);
return;
}
request.query("select deptid, deptname from departments", function(err, table) {
if (err) {
console.log(err);
return;
}
else {
console.log(table);
}
conn.close();
});
});
}
loadDepts();
Since this is a fairly visible answer, I wanted to add in a code snippet that worked for me with Trusted Connection. Got to it from getglad's edited answer.
const sql = require("mssql");
require("msnodesqlv8");
const conn = new sql.Connection({
database: "db_name",
server: "server_name",
driver: "msnodesqlv8",
options: {
trustedConnection: true
}
});
conn.connect().then(() => {
// ... sproc call, error catching, etc
// example: https://github.com/patriksimek/node-mssql#request
});
Using trusted connection, I was able to execute stored procedures, log the output, and close the connection without any trouble, and msnodesqlv8 has been updated more recently than any of the other drivers (latest release was October 2016 as of 11/3/2016), so that seems to be a safe choice as well.
And here's an example using mssql#4.0.4. The only changes are the initial require, which pull in msnodesqlv8 from within mssql, and sql.Connection is now sql.ConnectionPool. You will also need to change your stored procedure calls since the response is different, noted here. Credit to Jon's answer since he updated mine before I did!
const sql = require("mssql/msnodesqlv8");
const conn = new sql.ConnectionPool({
database: "db_name",
server: "server_name",
driver: "msnodesqlv8",
options: {
trustedConnection: true
}
});
conn.connect().then(() => {
// ... sproc call, error catching, etc
// example: https://github.com/patriksimek/node-mssql#request
});
I have been struggling too for some time about how to use mssql + Windows Auth, here is how i got it to work on my project.
As pointed out in the mssql documentation, you need msnodesqlv8 installed too.
npm install msnodesqlv8
Now, following on Aaron Ballard's answer, you use it like this:
const sql = require('mssql/msnodesqlv8')
const pool = new sql.ConnectionPool({
database: 'database',
server: 'server',
driver: 'msnodesqlv8',
options: {
trustedConnection: true
}
})
pool.connect().then(() => {
//simple query
pool.request().query('select 1 as number', (err, result) => {
console.dir(result)
})
})
As a note, i tried to add this as a comment on Aaron's answer, as mine is just a complement/update to his, but i don't have enough reputation to do so.
I have never been able to get mssql + windows auth to work for any of my projects. Try edge and edge-sql - it has worked for me. Be sure you install all the required packages.
https://github.com/tjanczuk/edge
https://github.com/tjanczuk/edge-sql
From there, it's pretty steamlined.
var edge = require('edge');
var params = {
connectionString: "Server=YourServer;Database=YourDB;Integrated Security=True",
source: "SELECT TOP 20 * FROM SampleData"
};
var getData = edge.func( 'sql', params);
getData(null, function (error, result) {
if (error) { console.log(error); return; }
if (result) {
console.log(result);
}
else {
console.log("No results");
}
});
EDIT
Well... 10 days after my original answer, apparently mssql added Windows Auth to the package. They heard our cries :) See here. I have not tested it yet, but it is officially in my backlog to test integration. I will report back.
FWTW, if mssql fits your needs, I would go with it, as 1) edge-sql has been dormant for 2 years and 2) the primary contributor has said he has left projects like this "in the caring hands of Microsoft", since he no longer works there.
EDIT 2
This keeps getting upvotes and there are comments saying some of the other answers' code examples either aren't working or aren't working on Windows.
This is my code using mssql, working on Windows, with msnodesqlv8 also installed:
var sql = require('mssql/msnodesqlv8');
var config = {
driver: 'msnodesqlv8',
connectionString: 'Driver={SQL Server Native Client XX.0};Server={SERVER\\NAME};Database={dbName};Trusted_Connection={yes};',
};
sql.connect(config)
.then(function() {
...profit...
})
.catch(function(err) {
// ... connect error checks
});
I've tried many variations and this is my complete solution.
I'm using SQL server Express.
I'm connecting, in the first instance, to the MASTER database only.
You only NEED to change "YOURINSTANCE\\SQLEXPRESS".
(Be sure to maintain the double-slash above!!!)
I'm using INTEGRATED SECURITY too.
The query relies on nothing at all (in your database).
You need to add your node packages
==> NPM INSTALL MSSQL and
==> NPM INSTALL msnodesqlv8
Hopefully, your connection issues will be a thing of the past.
Maybe.
Please.
// More here -> https://www.npmjs.com/package/mssql
var sql = require('mssql/msnodesqlv8');
var config = {
connectionString: 'Driver=SQL Server;Server=YOURINSTANCE\\SQLEXPRESS;Database=master;Trusted_Connection=true;'
};
sql.connect(config, err => {
new sql.Request().query('SELECT 1 AS justAnumber', (err, result) => {
console.log(".:The Good Place:.");
if(err) { // SQL error, but connection OK.
console.log(" Shirtballs: "+ err);
} else { // All is rosey in your garden.
console.dir(result);
};
});
});
sql.on('error', err => { // Connection borked.
console.log(".:The Bad Place:.");
console.log(" Fork: "+ err);
});
For me
I used connection setting as below
"server":"",
"domain":"", //sepcify domain of your user
"port": ,
"user":"", // enter username without domain
"password":"",
"database":""
and the TS code
import * as sql from 'mssql';
const pool = await new sql.ConnectionPool(connection).connect();
const result = await pool.request()
.query(`SELECT count(idpart) part_computed FROM demo.PARTs;`);
pool.close();
return Promise.resolve(result.recordset);
I could only get a Trusted Connection working using msnodesqlv8 (limited to Windows environments) with a connection string (rather than a config object).
const sql = require("msnodesqlv8");
const connectionString = function(databaseName) {
return "Server=.;Database=" + databaseName + ";Trusted_Connection=Yes;Driver={SQL Server Native Client 11.0}";
}
sql.query(connectionString("DatabaseName"), "SELECT * FROM dbo.Table1" , (err, recordset) => {
if(err) {
// Do something with the err object.
return;
}
// else
// Do something with the recordset object.
return;
});
Below code is working for me......
const sql = require('mssql/msnodesqlv8')
// config for your database
var config = {
driver: 'msnodesqlv8',
server: 'serverNAme\\SQLEXPRESS',
database: 'Learn' ,
options: {
trustedConnection: true
}
};
It worked for me
need to install msnodesqlv8 and mssql. also .......:)
var dbConfig = {
driver: 'msnodesqlv8',
server: "DESKTOP-66LO4I3",
database: "FutureHealthCareWeb",
user: "sa",
password: "pass#123",
options: {
trustedConnection: true
},
debug: true,
parseJSON: true
};
var sql = require('mssql/msnodesqlv8');
sql.connect(dbConfig, function (err) {
if (err) { console.log(JSON.stringify(err)+'..............') }
else {
console.log('Connected')
}
}
);
this worked for me
const sql = require("mssql/msnodesqlv8");
const conn = new sql.ConnectionPool({
database: "DB name",
server: "server name",
driver: "msnodesqlv8",
options: {
trustedConnection: true
}
});
conn.connect().then((err) => {
if(err) throw err;
else console.log("connected");
const req = new sql.Request(conn)
req.query("select * from table", function(error, res){
console.log(res)
})
});
I struggled to connect with mssql server which run in remote windows server using windows authentication mode . Then i found the solution just used like below code.
sql.connect("Data Source=172.25.x.x,1433;User Id=CSLx\\Name;Password=xxxxxx1234;Initial Catalog=giveTHedataabseNamel;Integrated Security=True",function(err){ }
I've just add domain: "DNAME", in config, and as result this config helps me connect to MS SQL with windows auth.
const config = {
driver: 'msnodesqlv8',
domain: "DNAME",
user: 'username',
password: 'pass',
server: '7.6.225.22',
database: 'DBNAME',
requestTimeout: 3600000, //an hour
options: {
trustedConnection: true
},
debug: true,
parseJSON: true
};
This version doesn't need a username or password.
To use windows authentication I installed mssql and msnodesqlv8.
Then in my app.js file:
const mssql = require('mssql/msnodesqlv8');
Note it is mssql not sql if you're using this example.
var config = {
database:'YOUR DATABASE NAME',
server: 'localhost\\SQLEXPRESS',
driver: 'msnodesqlv8',
options: {
trustedConnection: true,
enableArithAbort: true
}
};
You need to change the database name in config. Other than that it should work. My example:
app.get('/', function (req, res) {
mssql.connect(config, function (err) {
if (err) console.log(err);
var request = new mssql.Request();
request.query('select * from dbo.visit', function (err, result) {
if(err) console.log(err);
console.log(result);
});
});
});

Connecting NodeJS Express to MS SQL Server

I'm a NodeJS newbie and I am building an application that talks to an MSSQL (SQL Server 2008 R2) Database. For this, I tried using Sequelize, an ORM library that claims to do so.
While I have been successful in making it work with MySQL, SQL Server connection is just not working. I connected to a local database on both the occasions. Here's what I tried (as given in the docs):
[Part 1: Establish Connection]
... Express Code ...
var Sequelize = require('sequelize');
var sequelize = new Sequelize('NewDB', '', '', {
host: '(localdb)\v11.0',
dialect: 'mssql',
pool: {
max: 5,
min: 0,
idle: 10000
}
});
[Part 2: Testing]
var User = sequelize.define('user', {
firstName: {
type: Sequelize.STRING,
field: 'first_name' // Will result in an attribute that is firstName when user facing but first_name in the database
},
lastName: {
type: Sequelize.STRING
}
}, {
freezeTableName: true // Model tableName will be the same as the model name
});
User.sync({force: true}).then(function () {
// Table created
return User.create({
firstName: 'John',
lastName: 'Hancock'
});
});
... Express Code ...
The database NewDB does exist on the server. Now, While using SQL Server Express, the same credentials work. But not here. The error that I see is:
Unhandled rejection SequelizeConnectionError: Failed to connect to (localdb)\v11.0:1433 = getaddrinfo ENOTFOUND (localdb)\v11.0
So, here's the question. What credentials do I put, so that it works? And if it doesn't what would be alternate library to establish a Database connection? I'll prefer an ORM, but it's not that important a thing (anything works as long as I can connect to the DB).

Resources