Connect SQL Server with Next.js - node.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

Related

ELOGIN Error with Node.js and SQL Server database Connection

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);
})

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

node.js is not connecting to SQL Server database using SQL Server authentication

I'm using node.js and the mssql package to connect to a SQL Server database using SQL Server authentication. When I try connecting using SQL Server Management Studio with the same credentials, it is working fine. However, with node.js, I cannot login and get an error code ELOGIN with connection error.
I've tried many examples shown in google and I'm facing the same issue.
Let me know what I'm missing. Here is the code snippet of mine.
Code starts here
var sql = require('mssql');
var config = {
server: 'scaXXXXXXXXXXXX',
database: 'scaXXXXXXXXXX',
user: 'svcXXXXXXX',
password: 'Password',
port: 1433
};
function listProducts() {
var conn = new sql.ConnectionPool(config);
conn.connect().then(function () {
var request = new sql.Request(conn);
request.query("select top 1 * from dbo.Persons").then(function
(recordSet) {
console.log(recordSet);
conn.close();
}).catch(function (err) {
console.log(err);
conn.close();
});
}).catch(function (err) {
console.log(err);
});
}
listProducts();
This is the error while running this code:
ConnectionError: Login failed for user 'svcXXXXXXX'.
at Connection.tedious.once.err (C:\aws\node_modules\mssql\lib\tedious.js:244:17)
at Object.onceWrapper (events.js:277:13)
at Connection.emit (events.js:189:13)
at Connection.processLogin7Response (C:\aws\node_modules\tedious\lib\connection.js:1397:14)
at Connection.message (C:\aws\node_modules\tedious\lib\connection.js:1932:14)
at Connection.dispatchEvent (C:\aws\node_modules\tedious\lib\connection.js:1084:36)
at MessageIO.messageIo.on (C:\aws\node_modules\tedious\lib\connection.js:984:14)
at MessageIO.emit (events.js:189:13)
at Message.message.on (C:\aws\node_modules\tedious\lib\message-io.js:32:14)
at Message.emit (events.js:194:15)
code: 'ELOGIN',
originalError: { ConnectionError: Login failed for user 'svcXXXXXXX'.
at ConnectionError (C:\aws\node_modules\tedious\lib\errors.js:13:12)
at Parser.tokenStreamParser.on.token (C:\aws\node_modules\tedious\lib\connection.js:735:29)
at Parser.emit (events.js:189:13)
at Parser.parser.on.token (C:\aws\node_modules\tedious\lib\token\token-stream-parser.js:27:14)
at Parser.emit (events.js:189:13)
at addChunk (C:\aws\node_modules\readable-stream\lib_stream_readable.js:297:12)
at readableAddChunk (C:\aws\node_modules\readable-stream\lib_stream_readable.js:279:11)
at Parser.Readable.push (C:\aws\node_modules\readable-stream\lib_stream_readable.js:240:10)
at Parser.Transform.push (C:\aws\node_modules\readable-stream\lib_stream_transform.js:139:32)
at doneParsing (C:\aws\node_modules\tedious\lib\token\stream-parser.js:80:14)
message: 'Login failed for user \'svcXXXXXXX\'.',
code: 'ELOGIN' }, name: 'ConnectionError' }
I expect one record from database should extract and display.
it looks your login information is not correct.
did you write proper user name and password?
if your login info is correct, then check out login info has authority to be connected from the external environment
Try this out. It worked for me. If you are not doing with a localhost Database you need to be in that network. Make sure you can ping the database server.
var sql = require("mssql");
var moment = require("moment");
let port = process.env.PORT;
if (port == null || port == "") {
port = 8000;
}
var config = {
user: "xxxx",
password: "xxxxx",
server: "xxxxxx",
database: "xxxx"
};
const dbconn = sql.connect(config, err => {
if (!err) {
console.log("Connected to the database");
} else {
console.log("Problem in connecting to database");
console.log(err);
console.log("testing ");
}
});
app.get("/getSummaryDetails", (req, res) => {
dbconn.query("exec QCGrid", (err, rows, fields) => {
if (!err) {
res.send(rows.recordsets[0]);
}
});
});

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