Getting error while connecting database with nodejs - node.js

app.get('/', function (req, res) {
var config = {
//user: 'sa',
// password: '',
server: 'localhost',
database: 'TestDB',
debug: true
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from userInfo', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
//console.log(recordset);
sql.close();
});
});
});
I want to connect without user and password and Getting this error while executing through command prompt and there is some trusted connection query I can't find the please help
Error: Login failed for user ''.
at Connection.tedious.once.err (D:\Nodejs\UsersCreate\node_modules\mssql\lib\tedious.js:216:17)
at Object.onceWrapper (events.js:293:19)
at emitOne (events.js:96:13)
at Connection.emit (events.js:191:7)
at Connection.processLogin7Response (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connection.js:1148:16)
at Connection.message (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connection.js:1660:14)
at Connection.dispatchEvent (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connection.js:863:38)
at MessageIO.<anonymous> (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connection.js:757:18)
at emitNone (events.js:86:13)
at MessageIO.emit (events.js:188:7)
code: 'ELOGIN',
originalError:
{ ConnectionError: Login failed for user ''.
at ConnectionError (D:\Nodejs\UsersCreate\node_modules\tedious\lib\errors.js:12:12)
at Parser.<anonymous> (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connection.js:507:33)
at emitOne (events.js:96:13)
at Parser.emit (events.js:191:7)
at Parser.<anonymous> (D:\Nodejs\UsersCreate\node_modules\tedious\lib\token\token-stream-parser.js:54:15)
at emitOne (events.js:96:13)
at Parser.emit (events.js:191:7)
at addChunk (D:\Nodejs\UsersCreate\node_modules\tedious\node_modules\readable-stream\lib\_stream_readable.js:284:12)
at readableAddChunk (D:\Nodejs\UsersCreate\node_modules\tedious\node_modules\readable-stream\lib\_stream_readable.js:271:11)
at Parser.Readable.push (D:\Nodejs\UsersCreate\node_modules\tedious\node_modules\readable-stream\lib\_stream_readable.js:238:10) message: 'Login failed for user \'\'.', code: 'ELOGIN' },
name: 'ConnectionError' }
{ ConnectionError: Connection is closed.
at Request._query (D:\Nodejs\UsersCreate\node_modules\mssql\lib\base.js:1299:37)
at Request._query (D:\Nodejs\UsersCreate\node_modules\mssql\lib\tedious.js:497:11)
at Request.query (D:\Nodejs\UsersCreate\node_modules\mssql\lib\base.js:1242:12)
at D:\Nodejs\UsersCreate\app.js:119:17
at _poolCreate.then.catch.err (D:\Nodejs\UsersCreate\node_modules\mssql\lib\base.js:269:7)
at process._tickCallback (internal/process/next_tick.js:109:7) code: 'ECONNCLOSED', name: 'ConnectionError' }
GET / 200 36.940 ms - -
Please help me on this and want to connect this database using window authentication

You can try with:
options: {
trustedConnection: true
}

First install NPM Package,
npm install msnodesqlv8
Then change your config variable as,
const sql = require('mssql/msnodesqlv8')
var config = {
server: 'localhost',
driver: 'msnodesqlv8',
database: 'TestDB',
debug: true,
options: {
trustedConnection: true
}
};

Related

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

Unknown command when using promise-ftp in node

I'm trying to use a promise approach when interacting with my ftp server. I'm using the node package 'promise-ftp' v1.3.5.
The code I have is as follows:
const appFeedBuffer = Buffer.from('somedatastring', 'utf8');
var Client = require('promise-ftp');
var ftpClient = new Client();
ftpClient.connect({ host: 'myHost', user: 'me', password: 'mypassword' })
.then(() => {
return ftpClient.mkdir('newDir')
}).then(() => {
return ftpClient.put(appFeedBuffer, 'fileName')
}).then(()=> {
return ftpClient.rmdir('oldDir')
}).then(() => {
return ftpClient.rename('newDir', 'oldDir')
}).then(() => {
return ftpClient.end();
}).catch(err => {
console.log("something went wrong: " + err);
res.status(500).send('SERVER ERROR');
});
The problem is the put command - I get the error 'UNKNOWN COMMAND' which appears to come from the #icetee/ftp library, of which promise-ftp is a dependant. put is most certainly a valid command in the promise-ftp library!
Stack:
Unhandled rejection Error: Unknown command
at makeError (/Users/projects/ftpProject/node_modules/#icetee/ftp/lib/connection.js:1128:13)
at Parser.<anonymous> (/Users/projects/ftpProject/node_modules/#icetee/ftp/lib/connection.js:122:25)
at emitTwo (events.js:126:13)
at Parser.emit (events.js:214:7)
at Parser._write (/Users/projects/ftpProject/node_modules/#icetee/ftp/lib/parser.js:61:10)
at doWrite (_stream_writable.js:397:12)
at writeOrBuffer (_stream_writable.js:383:5)
at Parser.Writable.write (_stream_writable.js:290:11)
at Socket.ondata (/Users/projects/ftpProject/node_modules/#icetee/ftp/lib/connection.js:298:20)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at addChunk (_stream_readable.js:263:12)
at readableAddChunk (_stream_readable.js:250:11)
at Socket.Readable.push (_stream_readable.js:208:10)
at TCP.onread (net.js:597:20)
I can't find anyone else having this problem. What am I doing wrong?

trying to connect SQL using node js

app.get('/', function (req, res) {
var config = {
user: 'sa',
password: '',
server: 'localhost',
database: 'TestDB'
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from userInfo', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
console.log(recordset);
});
});
});
Getting this error in command prompt
{ Error: Failed to connect to localhost:1433 - Could not connect (sequence)
at Connection.tedious.once.err (D:\Nodejs\UsersCreate\node_modules\mssql\lib\tedious.js:216:17)
at Object.onceWrapper (events.js:293:19)
at emitOne (events.js:96:13)
at Connection.emit (events.js:191:7)
at Connection.socketError (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connection.js:875:14)
at D:\Nodejs\UsersCreate\node_modules\tedious\lib\connection.js:740:25
at SequentialConnectionStrategy.connect (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connector.js:153:9)
at Socket.onError (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connector.js:169:16)
at emitOne (events.js:96:13)
at Socket.emit (events.js:191:7)
code: 'ESOCKET',
originalError:
{ ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at ConnectionError (D:\Nodejs\UsersCreate\node_modules\tedious\lib\errors.js:12:12)
at Connection.socketError (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connection.js:875:30)
at D:\Nodejs\UsersCreate\node_modules\tedious\lib\connection.js:740:25
at SequentialConnectionStrategy.connect (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connector.js:153:9)
at Socket.onError (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connector.js:169:16)
at emitOne (events.js:96:13)
at Socket.emit (events.js:191:7)
at emitErrorNT (net.js:1284:8)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
message: 'Failed to connect to localhost:1433 - Could not connect (sequence)',
code: 'ESOCKET' },
name: 'ConnectionError' }
{ ConnectionError: Connection is closed.
at Request._query (D:\Nodejs\UsersCreate\node_modules\mssql\lib\base.js:1299:37)
at Request._query (D:\Nodejs\UsersCreate\node_modules\mssql\lib\tedious.js:497:11)
at Request.query (D:\Nodejs\UsersCreate\node_modules\mssql\lib\base.js:1242:12)
at D:\Nodejs\UsersCreate\app.js:118:17
at _poolCreate.then.catch.err (D:\Nodejs\UsersCreate\node_modules\mssql\lib\base.js:269:7)
at process._tickCallback (internal/process/next_tick.js:109:7) code: 'ECONNCLOSED', name: 'ConnectionError' }
undefined
Please help me on this error and need navigation to rectify this error

Node Driver MongoDb - handleCallbaak is not defined instead of catch() firing

Using Node 8.* and MongoDb driver mongodb#2.2.31
I am testing the my code base to see how it behaves if my MongoDB ever crashes. The way I test is to turn the MongoDB daemon off.
The catch() statement is not executing. Instead I get the mongodb driver error ReferenceError: handleCallbaak is not defined when mongo.tempUsers.add(body, token, password) executes.
Why is this? Shouldn't the catch() execute?
TempUsers.prototype.add = function(body, token) {
const user = { "email" : body.email };
return this.collection.updateOne(user,
{ $set: {
"token": token,
"createdAt": new Date(),
}
},
{
writeConcern: true,
maxTimeMS: QUERY_TIME,
upsert: true
}
);
const confirmUser = (body, password) => {
const token = uuidv4();
const result = mongo.tempUsers.add(body, token, password);
result.then(() => sendConfirmationEmail(body, token)).catch(e => console.log(e));
};
UPDATE: How my own collections object is created:
var collections = {
tempUsers: false
};
function connect(dbURI) {
return MongoClient
.connect(dbURI)
.then(function(db) {
console.log(colors
.bold('MongoDB default connection open to ' + dbURI));
initDbListeners(db);
initCollections(db);
return db;
})
.catch(function(err) {
console.log(colors
.red(err));
});
}
function initCollections(db) {
collections.tempUsers = new TempUsers(db);
}
module.exports.collections = collections;
/home/one/github/dolphin/node_modules/mongodb/lib/collection.js:1057
if(err) return handleCallbaak(callback, err, null);
^
ReferenceError: handleCallbaak is not defined
at Object.c (/home/one/github/dolphin/node_modules/mongodb/lib/collection.js:1057:13)
at Store.flush (/home/one/github/dolphin/node_modules/mongodb/lib/topology_base.js:68:30)
at Server.reconnectFailedHandler (/home/one/github/dolphin/node_modules/mongodb/lib/server.js:290:18)
at emitOne (events.js:115:13)
at Server.emit (events.js:210:7)
at Pool.<anonymous> (/home/one/github/dolphin/node_modules/mongodb-core/lib/topologies/server.js:324:14)
at emitOne (events.js:115:13)
at Pool.emit (events.js:210:7)
at Connection.<anonymous> (/home/one/github/dolphin/node_modules/mongodb-core/lib/connection/pool.js:317:16)
at emitTwo (events.js:125:13)
at Connection.emit (events.js:213:7)
at Socket.<anonymous> (/home/one/github/dolphin/node_modules/mongodb-core/lib/connection/connection.js:187:49)
at Object.onceWrapper (events.js:316:30)
at emitOne (events.js:115:13)
at Socket.emit (events.js:210:7)
at emitErrorNT (internal/streams/destroy.js:64:8)
The mongodb node_modules/mongodb/lib/collection.js file on your system is different from the released file.
Remove the /home/one/github/dolphin/node_modules/mongodb directory from your project and run npm install again.

Resources