ELOGIN Error with Node.js and SQL Server database Connection - node.js

I am trying to connect my SQL Database which is in sql server management studio to Node.js. Currently, the connection is being done locally on my machine. This is the error which I keep on getting:
undefined
[nodemon] clean exit - waiting for changes before restart
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
ConnectionError: Login failed for user 'database access'.
at C:\Users\User\Desktop\PROGRAMMING\Aviation Calc\calc\node_modules\mssql\lib\tedious\connection-pool.js:70:17
at Connection.onConnect (C:\Users\User\Desktop\PROGRAMMING\Aviation Calc\calc\node_modules\tedious\lib\connection.js:1051:9)
at Object.onceWrapper (node:events:510:26)
at Connection.emit (node:events:390:28)
at Connection.emit (C:\Users\User\Desktop\PROGRAMMING\Aviation Calc\calc\node_modules\tedious\lib\connection.js:1079:18)
at C:\Users\User\Desktop\PROGRAMMING\Aviation Calc\calc\node_modules\tedious\lib\connection.js:2608:18
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ELOGIN',
originalError: ConnectionError: Login failed for user 'database access'.
at Login7TokenHandler.onErrorMessage (C:\Users\User\Desktop\PROGRAMMING\Aviation Calc\calc\node_modules\tedious\lib\token\handler.js:245:19)
at Readable.<anonymous> (C:\Users\User\Desktop\PROGRAMMING\Aviation Calc\calc\node_modules\tedious\lib\token\token-stream-parser.js:26:33)
at Readable.emit (node:events:390:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Readable.push (node:internal/streams/readable:228:10)
at next (node:internal/streams/from:98:31)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ELOGIN',
isTransient: undefined
}
}
NOT CONNECTED
undefined
[nodemon] clean exit - waiting for changes before restart
At first I thought that this may be ocurring because I havent enabled windows firewall to allow my port: 1433 but even after doing that I kept on getting the same error message. I also made sure to enable the SQL Server Services in SQL Configuration Manager.
Here is my code:
dbConfig.js
const config = {
// dialect: 'mssql',
user: 'database access',
password: 'tronn6215',
// DESKTOP-NKHJ1GI
// SQLQuery1.sql
server: 'DESKTOP-NKHJ1GI',
database: 'Avtag Data',
options: {
trustServerCertificate: true,
trustedConnection: false,
enableArithAbort: true,
instancename: 'SQLEXPRESS'
},
// dynamic_port: 51582 (dynamic port num)
// port: 50381
port: 1433
//have enabled window firewall to allow static port 1433 for connection but still error
//Now error- code: 'ELOGIN'
}
module.exports = config;
dbOperation.js
const config = require('./dbConfig'),
sql = require('mssql');
const getEntryPoint = async() => {
try {
let pool = await sql.connect(config);
let entry = pool.request().query("SELECT * from ENTRY _POINT1")
console.log(entry);
console.log('CONNECTED')
return entry;
}
catch(error) {
console.log(error);
console.log('NOT CONNECTED')
}
}
module.exports = {
getEntryPoint
}
server.js
const express = require('express'),
dbOperation = require('./dbFiles/dbOperation'),
cors = require('cors');
dbOperation.getEntryPoint().then(res => {
console.log(res);
})

Related

Connect SQL Server with Next.js

I am having a problem (ConnectionError) while trying to connect Next.js with SQL Server with mssql, I have enabled TCP/IP, and SQL Server Browser is running.
this is my code:
// db.js
import sql from 'mssql'
// connection configs
const config = {
user: 'test',
password: '1000',
server: '.\sqlexpress',
database: 'DATABASE_NAME',
port: 1433,
options: {
instancename: 'SQLEXPRESS',
trustedconnection: true,
trustServerCertificate: true
},
}
export default async function ExcuteQuery(query, options) {
try {
let pool = await sql.connect(config);
let products = await pool.request().query(query);
return products.recordsets;
}
catch (error) {
console.log(error);
}
}
// api/hello.js
import ExcuteQuery from '../../utils/db';
export default async function handler(req, res) {
console.log(await ExcuteQuery('select * from tbl_category'));
res.status(200).json({})
}
this is the error:
ConnectionError: getaddrinfo ENOTFOUND .
at E:\0 - WEB\pos\node_modules\mssql\lib\tedious\connection-pool.js:70:17
at Connection.onConnect (E:\0 - WEB\pos\node_modules\tedious\lib\connection.js:1012:9)
at Object.onceWrapper (node:events:628:26)
at Connection.emit (node:events:513:28)
at Connection.emit (E:\0 - WEB\pos\node_modules\tedious\lib\connection.js:1040:18)
at E:\0 - WEB\pos\node_modules\tedious\lib\connection.js:1081:16
at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
code: 'EINSTLOOKUP',
originalError: ConnectionError: getaddrinfo ENOTFOUND .
at E:\0 - WEB\pos\node_modules\tedious\lib\connection.js:1081:32
at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
code: 'EINSTLOOKUP',
isTransient: undefined
}
}
also these are the settings changed:
I tried setting the server to MY_DESKTOP_NAME\SQLEXPRESS but it didn't work, but after disabling and reenabling all the settings it works now, it was kinda like a glitch in the system

ELOGIN error while connecting to the SQL server

I'm learning full stack web development and was trying to connect to SQL server from my backend Node.js. I was following an online video. While running the index.js file I get the below error -
ConnectionError: Login failed for user 'systemadmin'.
at C:\Users\akunjalw\Desktop\FullStack\server\node_modules\mssql\lib\tedious\connection-pool.js:70:17
at Connection.onConnect (C:\Users\akunjalw\Desktop\FullStack\server\node_modules\tedious\lib\connection.js:1038:9)
at Object.onceWrapper (node:events:640:26)
at Connection.emit (node:events:520:28)
at Connection.emit (C:\Users\akunjalw\Desktop\FullStack\server\node_modules\tedious\lib\connection.js:1066:18)
at Parser.<anonymous> (C:\Users\akunjalw\Desktop\FullStack\server\node_modules\tedious\lib\connection.js:2574:20)
at Object.onceWrapper (node:events:639:28)
at Parser.emit (node:events:520:28)
at Readable.<anonymous> (C:\Users\akunjalw\Desktop\FullStack\server\node_modules\tedious\lib\token\token-stream-parser.js:32:12)
at Readable.emit (node:events:520:28) {
code: 'ELOGIN',
originalError: ConnectionError: Login failed for user 'systemadmin'.
at Login7TokenHandler.onErrorMessage (C:\Users\akunjalw\Desktop\FullStack\server\node_modules\tedious\lib\token\handler.js:239:19)
at Readable.<anonymous> (C:\Users\akunjalw\Desktop\FullStack\server\node_modules\tedious\lib\token\token-stream-parser.js:26:33)
at Readable.emit (node:events:520:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Readable.push (node:internal/streams/readable:228:10)
at next (node:internal/streams/from:98:31)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ELOGIN',
isTransient: undefined
}
}
undefined
[nodemon] clean exit - waiting for changes before restart
The code is as follows
const sql = require("mssql");
const config = {
user: "systemadmin",
password: "R#jasthaan1212",
server: "localhost",
database: "ORG_EMPLOYEEDATA",
options: {
trustedconnection: true,
trustServerCertificate: true,
enableArithAbort: true,
instancename: "SQL2019",
},
port: 50685,
};
async function getEmployeeName() {
try {
let pool = await sql.connect(config);
let employeeData = await pool
.request()
.query("select * from dbo.EMPLOYEES_DATA");
return employeeData.recordsets;
} catch (error) {
console.log(error);
}
}
module.exports = { getEmployeeName: getEmployeeName };
const dboperations = require("./dboperations");
dboperations.getEmployeeName().then((result) => {
console.log(result);
});
Please let me know what exactly I'm missing here. I couldn't find the way to resolve this by searching in internet as well, may be I'm terrible at searching. Any help to resolve this is appreciated.

Problem connecting postgreSQL with Knex - assert.fail(`unknown message code: ${code.toString(16)}`)

I'm totally new to relational databases and I'm trying to build a node and express project with postgres using knex.
I'm getting the following error when trying to connect to postgres:
/home/German/Desktop/ger/code/projects/mixr/mixr-back/node_modules/pg-protocol/src/parser.ts:202
assert.fail(`unknown message code: ${code.toString(16)}`)
^
AssertionError [ERR_ASSERTION]: unknown message code: 5b
at Parser.handlePacket (/home/German/Desktop/ger/code/projects/mixr/mixr-back/node_modules/pg-protocol/src/parser.ts:202:16)
at Parser.parse (/home/German/Desktop/ger/code/projects/mixr/mixr-back/node_modules/pg-protocol/src/parser.ts:103:30)
at Socket.<anonymous> (/home/German/Desktop/ger/code/projects/mixr/mixr-back/node_modules/pg-protocol/src/index.ts:7:48)
at Socket.emit (node:events:394:28)
at Socket.emit (node:domain:475:12)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)
at TCP.onStreamRead (node:internal/stream_base_commons:199:23) {
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: undefined,
expected: undefined,
operator: 'fail'
}
I understand it's a connection problem, but I'm not sure why I'm getting this.
This is my connection code:
export const knex = require('knex')({
client: 'pg',
connection: {
host : 'localhost',
port : 3306,
user : 'notTheRealUser',
password : 'notTheRealPassword',
database : 'pgdb'
}
})
knex.raw("SELECT 1").then(() => {
console.log("PostgreSQL connected")
})
.catch((e: Error) => {
console.log("PostgreSQL not connected")
console.error(e)
})
And then I'm importing the Knex object on the different routes to make queries, like so:
import { knex } from '../db/db'
router.post('/register', async (req: Request, res: Response) => {
// Check if the email isn't already taken
try {
const emailIsTaken = await knex('users').where({ email: req.body.email })
if (emailIsTaken) return res.status(500).json('Email already used')
} catch (err) {
res.status(500).send(err)
console.error(err)
}
})
Full code can be found here: https://github.com/coccagerman/mixr-back
you are using MySQL port 3306,
PostgresQL uses port 5432

Connect to a remote server mongoDB in Docker via ssh in nodeJS using tunnel-ssh, AuthenticationFailed

I am trying to connect to a remote server MongoDB in Docker through ssh in Nodejs as below :
sshConfig = {
username: 'username',
password: 'password',
host: 'host',
port: 22,
dstHost: '172.17.0.3',
dstPort: 27017,
localPort: 5000
};
const uri = 'mongodb://admin:password#localhost:27017/admin';
tunnel(sshConfig, async error => {
if (error) {
throw new Error(`SSH connection error: ${error}`);
}
const client = new MongoClient(uri);
async function run() {
try {
// Connect the client to the server
await client.connect();
// Establish and verify connection
await client.db('admin').command({ ping: 1 });
console.log('Connected successfully to server');
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
await run().catch(console.dir);
});
But I am getting error as below :
MongoServerError: Authentication failed.
at MessageStream.messageHandler (/node_modules/mongodb/src/cmap/connection.ts:740:20)
at MessageStream.emit (node:events:390:28)
at MessageStream.emit (node:domain:475:12)
at processIncomingData (/node_modules/mongodb/src/cmap/message_stream.ts:167:12)
at MessageStream._write (/node_modules/mongodb/src/cmap/message_stream.ts:64:5)
at writeOrBuffer (node:internal/streams/writable:389:12)
at _write (node:internal/streams/writable:330:10)
at MessageStream.Writable.write (node:internal/streams/writable:334:10)
at Socket.ondata (node:internal/streams/readable:754:22)
at Socket.emit (node:events:390:28) {
ok: 0,
code: 18,
codeName: 'AuthenticationFailed'
},
and I open http://localhost:5000/ by browser, it shows that:
It looks like you are trying to access MongoDB over HTTP on the native driver port.
I can connect the database via:
Use MongoDB compass to connect the database via ssh
Use mongo 'mongodb://admin:password#remote-host:27017/admin' in local machine terminal
Use MongoClient(mongodb://admin:password#remote-host:27017/admin) in Nodejs without ssh-tunnel
Use mongo 'mongodb://admin:password#localhost:27017/admin' in both remote host and remote host docker contaniner
I am sure the password is correct.

Unable to connect to Microsoft SQL Server using Node.js,mssql and express

I am trying to learn Node.js and created a simple project to query the local database. But I get failed to look up an instance error message.
I have checked that the SQL Server services running in services.msc
I have verified TCP/IP is enabled
I have tried with the username and password and without it as well. I connect to localdb in SQL Server Management Studio as (localdb)\v11.0 and below is the screenshot of the properties
What am I doing incorrectly? What should be actual username and password? What should be the servername?
const sql = require('mssql');
// config for your database
const config = {
user: 'mywindows username',
password: 'my windows password',
server: '(localdb)\\v11.0',
database: 'test',
options: {
encrypt: true
}
};
console.log('starting sql');
var connection = new sql.connect(config, function(err) {
console.log(err);
var request = new sql.Request(connection);
request.query('select * from employees', function(err, recordset) {
if(err) // ... error checks
console.log('Database connection error');
console.dir("User Data: "+recordset);
});
});
sql.close();
console.log('ending sql');
});
app.listen(3002, () => {
console.log('Listening on port 3002');})
Below is the error message
{ ConnectionError: Failed to lookup instance on (localdb) -
getaddrinfo ENOTFOUND (localdb)
at Connection.tedious.once.err (C:\Users\vndbsubramaniam\Desktop\React
projects\ReactWithSql\node_modules\mssql\lib\tedious.js:244:17)
at Object.onceWrapper (events.js:285:13)
at Connection.emit (events.js:197:13)
at InstanceLookup.instanceLookup (C:\Users\vndbsubramaniam\Desktop\React
projects\ReactWithSql\node_modules\tedious\lib\connection.js:945:16)
at sender.execute (C:\Users\vndbsubramaniam\Desktop\React projects\ReactWithSql\node_modules\tedious\lib\instance-lookup.js:66:13)
at GetAddrInfoReqWrap.invokeLookupAll [as callback] (C:\Users\vndbsubramaniam\Desktop\React
projects\ReactWithSql\node_modules\tedious\lib\sender.js:43:16)
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (dns.js:70:17) code: 'EINSTLOOKUP', originalError: { ConnectionError: Failed to
lookup instance on (localdb) - getaddrinfo ENOTFOUND (localdb)
at ConnectionError (C:\Users\vndbsubramaniam\Desktop\React projects\ReactWithSql\node_modules\tedious\lib\errors.js:13:12)
at InstanceLookup.instanceLookup (C:\Users\vndbsubramaniam\Desktop\React
projects\ReactWithSql\node_modules\tedious\lib\connection.js:945:32)
at sender.execute (C:\Users\vndbsubramaniam\Desktop\React projects\ReactWithSql\node_modules\tedious\lib\instance-lookup.js:66:13)
at GetAddrInfoReqWrap.invokeLookupAll [as callback] (C:\Users\vndbsubramaniam\Desktop\React
projects\ReactWithSql\node_modules\tedious\lib\sender.js:43:16)
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (dns.js:70:17)
message:
'Failed to lookup instance on (localdb) - getaddrinfo ENOTFOUND (localdb)',
code: 'EINSTLOOKUP' }, name: 'ConnectionError' } Database connection error
After struggling for hours on this one finally found the answer here SQL to Node connection
It seems i have to add msnodesqlv8 package and use add the driver syntax to the config.
app.get('/test', (req, res) => {
const sql = require('mssql/msnodesqlv8');
// config for your database
const config = {
database: 'test',
server: '(localdb)\\v11.0',
driver: 'msnodesqlv8',
options : {
trustedConnection : true
}
};
console.log('starting sql');
const pool = new sql.ConnectionPool(config);
pool.connect().then(() => {
//simple query
pool.request().query('select * from employees', (err, result) => {
if(err) res.send(err)
else{
return res.json({
data : result.recordset
})
}
})
sql.close();
})
console.log('ending sql');
});
you will need msnodesqlv8 driver, which you have to paste it in require as
var sql = require('mssql/msnodesqlv8'),
as well as you will have to include it in driver section in config object.
var config = {
user:"*****",
password:"*****",
database:"*****",
driver: 'msnodesqlv8',
server:"*****",
options: {
trustedConnection : true
}
}

Resources