MongoDB ECONNRESET error - node.js

I'm trying to setup a basic mongodb connection, but I get an ECONNRESET error. I've researched a bit and found similar questions and answers but haven't found a solution.
Code:
'use strict';
const Hapi = require('hapi');
const hapiMongo = require('hapi-mongodb');
var server = new Hapi.Server();
server.connection({
port: '1111'
});
server.route({
method: 'GET',
path: '/',
config: {
cors: true,
handler: (request, reply) => {
var db = request.server.plugins['hapi-mongodb'].db;
reply('Hello World' + db);
}
}
});
server.register({
register: hapiMongo,
options: {
"url": "mongodb://username:psswd#ds011308.mongolab.com:11308/heroku_jg542kf4",
"settings": {
"db": {
"native_parser": false
}
}
}
}, (err) => {
if (err) {
console.error(err);
throw err;
}
server.start((err) => console.log('Served at:', server.info.uri));
})
Console error:
{ [MongoError: server ds011308-a.mongolab.com:11308 received an error
{"name":"M ongoError","message":"read ECONNRESET"}] name:
'MongoError', message: 'server ds011308-a.mongolab.com:11308
received an error {"name":"Mong oError","message":"read ECONNRESET"}'
}
C:\Users\username\Desktop\code\hapi-mongo\node_modules\mongodb\lib\mongo_client.js:4
54
throw err
^ MongoError: server ds011308-a.mongolab.com:11308 received an error {"name":"Mon goError","message":"read ECONNRESET"}
at null. (C:\Users\username\Desktop\code\hapi-mongo\node_modules\mong
odb-core\lib\topologies\server.js:297:40)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at null. (C:\Users\username\Desktop\code\hapi-mongo\node_modules\mong
odb-core\lib\connection\pool.js:132:12)
at g (events.js:260:16)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at Socket. (C:\Users\username\Desktop\code\hapi-mongo\node_modules\mo
ngodb-core\lib\connection\connection.js:132:49)
at Socket.g (events.js:260:16)
at emitOne (events.js:77:13)
Any pointers on how I can fix this?

Related

Node.js redis#4 Upgrade: SocketClosedUnexpectedlyError: Socket closed unexpectedly

I've got some legacy code that I'm upgrading from version 3 of the Node.js redis library to version 4 of the Node.js redis library. The basic shape of the code looks like this
var redis = require('redis')
var client = redis.createClient({
port: '6379',
host: process.env.REDIS_HOST,
legacyMode: true
})
client.connect()
client.flushall(function (err, reply) {
client.hkeys('hash key', function (err, replies) {
console.log("key set done")
client.quit()
})
})
console.log("main done")
When I run this code with redis#4.3.1, I get the following error, and node.js exits with a non-zero status code
main done
key set done
events.js:292
throw er; // Unhandled 'error' event
^
SocketClosedUnexpectedlyError: Socket closed unexpectedly
at Socket.<anonymous> (/Users/astorm/Documents/redis4/node_modules/#redis/client/dist/lib/client/socket.js:182:118)
at Object.onceWrapper (events.js:422:26)
at Socket.emit (events.js:315:20)
at TCP.<anonymous> (net.js:673:12)
Emitted 'error' event on Commander instance at:
at RedisSocket.<anonymous> (/Users/astorm/Documents/redis4/node_modules/#redis/client/dist/lib/client/index.js:350:14)
at RedisSocket.emit (events.js:315:20)
at RedisSocket._RedisSocket_onSocketError (/Users/astorm/Documents/redis4/node_modules/#redis/client/dist/lib/client/socket.js:205:10)
at Socket.<anonymous> (/Users/astorm/Documents/redis4/node_modules/#redis/client/dist/lib/client/socket.js:182:107)
at Object.onceWrapper (events.js:422:26)
at Socket.emit (events.js:315:20)
at TCP.<anonymous> (net.js:673:12)
While in redis#3.1.2 it runs (minus the client.connect()) without issue.
I've been able to work around this by replacing client.quit() with client.disconnect(), but the actual code is a little more complex than the above example and I'd rather use the graceful shutdown of client.quit than the harsher "SHUT IT DOWN NOW" of client.disconnect().
Does anyone know what the issue here might be? Why is redis#4 failing with a SocketClosedUnexpectedlyError: Socket closed unexpectedly error.
What I found so far is that after a while (keepAlive default is 5 minutes) without any requests the Redis client closes and throws an error event, but if you don't handle this event it will crash your application.
My solution for that was:
/* eslint-disable no-inline-comments */
import type { RedisClientType } from 'redis'
import { createClient } from 'redis'
import { config } from '#app/config'
import { logger } from '#app/utils/logger'
let redisClient: RedisClientType
let isReady: boolean
const cacheOptions = {
url: config.redis.tlsFlag ? config.redis.urlTls : config.redis.url,
}
if (config.redis.tlsFlag) {
Object.assign(cacheOptions, {
socket: {
// keepAlive: 300, // 5 minutes DEFAULT
tls: false,
},
})
}
async function getCache(): Promise<RedisClientType> {
if (!isReady) {
redisClient = createClient({
...cacheOptions,
})
redisClient.on('error', err => logger.error(`Redis Error: ${err}`))
redisClient.on('connect', () => logger.info('Redis connected'))
redisClient.on('reconnecting', () => logger.info('Redis reconnecting'))
redisClient.on('ready', () => {
isReady = true
logger.info('Redis ready!')
})
await redisClient.connect()
}
return redisClient
}
getCache().then(connection => {
redisClient = connection
}).catch(err => {
// eslint-disable-next-line #typescript-eslint/no-unsafe-assignment
logger.error({ err }, 'Failed to connect to Redis')
})
export {
getCache,
}
anyway... in your situation try to handle the error event
client.on('error', err => logger.error(`Redis Error: ${err}`))

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 Events Emitter on net.createserver

So i got a problem and stuck around 3 days, i'm using node js as a socket server to receive string and processing some json data to give a string response to socket client, stack used in node js(net, events), my code have no problem for the first request, but after the second request it got an error like this(server):
[2020-12-23T07:45:13.821Z] server listening on port: 4444
[2020-12-23T07:45:15.696Z] New Connection : ::ffff:127.0.0.1
[2020-12-23T07:45:15.701Z] message: string
[2020-12-23T07:45:15.702Z] executing call function
[2020-12-23T07:45:15.703Z] oncall function
[2020-12-23T07:45:15.703Z] executing emit
[2020-12-23T07:45:15.704Z] {
orig: 'orig',
origParam: { number: '123456' },
resp: [
{
content: [Array],
firstPage: true,
lastPage: true,
number: 0,
numberOfElements: 1,
size: 1,
sort: null,
totalElements: 1
},
{ result: 'UNMATCHED' }
]
}
[2020-12-23T07:45:15.707Z] Returning : diterima
[2020-12-23T07:45:42.403Z] New Connection : ::ffff:127.0.0.1
[2020-12-23T07:45:42.407Z] message: string
[2020-12-23T07:45:42.408Z] executing call function
[2020-12-23T07:45:42.408Z] oncall function
[2020-12-23T07:45:42.409Z] executing emit
[2020-12-23T07:45:42.409Z] {
orig: 'orig',
origParam: { number: '123456' },
resp: [
{
content: [Array],
firstPage: true,
lastPage: true,
number: 0,
numberOfElements: 1,
size: 1,
sort: null,
totalElements: 1
},
{ result: 'UNMATCHED' }
]
}
[2020-12-23T07:45:42.410Z] Returning : diterima
[2020-12-23T07:45:42.411Z] {
orig: 'orig',
origParam: { number: '123456' },
resp: [
{
content: [Array],
firstPage: true,
lastPage: true,
number: 0,
numberOfElements: 1,
size: 1,
sort: null,
totalElements: 1
},
{ result: 'UNMATCHED' }
]
}
[2020-12-23T07:45:42.412Z] Returning : diterima
events.js:288
throw er; // Unhandled 'error' event
^
Error: This socket has been ended by the other party
at Socket.writeAfterFIN [as write] (net.js:451:14)
at HanaconsResponded.<anonymous> (C:\Users\ralfian\--\--\--.js:47:11)
at HanaconsResponded.emit (events.js:323:22)
at callFunction (C:\Users\ralfian\--\--\--.js:79:23)
at Socket.<anonymous> (C:\Users\ralfian\--\--\--.js:35:17)
at Socket.emit (events.js:311:20)
at addChunk (_stream_readable.js:294:12)
at readableAddChunk (_stream_readable.js:271:13)
at Socket.Readable.push (_stream_readable.js:209:10)
at TCP.onStreamRead (internal/stream_base_commons.js:186:23)
Emitted 'error' event on Socket instance at:
at emitErrorNT (net.js:1336:8)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
code: 'EPIPE'
}
and bellow is error on the client side at second request, (first request have no problem):
CLIENT: I connected to the server.
{"orig":"orig","origParam":{"number":"123456"},"resp":[{"content":[{"gender":"not match"}],"firstPage":true,"lastPage":true,"number":0,"numb
erOfElements":1,"size":1,"sort":null,"totalElements":1},{"result":"UNMATCHED"}]}
events.js:288
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:205:27)
Emitted 'error' event on Socket instance at:
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
errno: 'ECONNRESET',
code: 'ECONNRESET',
syscall: 'read'
}
Here is my server Code:
var net = require('net');
var server = net.createServer();
require('log-timestamp');
var hostport = 4444;
var EventEmitter = require('events');
class CheckResponded extends EventEmitter {}
var checkResponded = new CheckResponded();
server.listen({
port : hostport,
exclusive: true
},);
console.log('server listening on ' + 'port: ' + hostport);
server.on('connection', (e) => {
console.log( 'New Connection : ' + e.remoteAddress );
e.setEncoding('utf8');
e.setTimeout(60000);
e.on('end', () => {})
e.on( 'timeout', () => {
console.log('Socket Timeout. Reseting.');
e.end();
});
e.on( 'data', (buff) => {
console.log("message: " + typeof buff);
try {
if (buff === "exec"){
console.log("executing call function")
callFunction()
}
} catch(error){
console.log('error on socket -> ' + error)
}
});
checkResponded.on( 'event1', (f) => {
console.log(f)
var rmsg;
rmsg = f;
console.log("Returning : " + 'diterima');
e.write(JSON.stringify(rmsg));
});
});
function callFunction() {
console.log('oncall function')
var imsg = {
"orig": "orig",
"origParam": {
"number": "123456",
},
"resp": [
{
"content": [
{
"gender": "not match",
}
],
"firstPage": true,
"lastPage": true,
"number": 0,
"numberOfElements": 1,
"size": 1,
"sort": null,
"totalElements": 1
},
{
"result": "UNMATCHED"
}
]
}
console.log('executing emit')
checkResponded.emit('event1', imsg);
return
}
and bellow is the client request example:
const net = require('net');
var host = 'localhost';
const client = net.createConnection({ port: 4444, host: host }, () => {
console.log('CLIENT: I connected to the server.');
client.write('exec')
});
client.on('data', (data) => {
console.log(data.toString());
client.end();
});
client.on('end', () => {
console.log('CLIENT: I disconnected from the server.');
});
looking for help , Thanks!
One thing I see is that your client code assumes that your entire response arrives in one data event. That is not a safe assumption. It may sometimes happen that way, but it is not guaranteed and if the server is not done sending data when you call client.end(), you will get an error (like you are) on the server such as:
Error: This socket has been ended by the other party
You will need some sort of protocol in the data you send so that you can parse the incoming data and you can then know when you have a complete response and when you need to wait for the rest of the data to arrive.
Similar issue discussed here: Detect complete data received on 'data' Event in Net module of Node.js

Getting error while connecting database with nodejs

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

Resources