Getting "InternalServerError" while using Mongo with Node js - node.js

I am new to Node js programming. Trying to write a simple user create using.. code along with the stack track is given below. Appreciate any help as to what is causing this..
users-add.mjs:
'use strict';
const util = require('util');
const restify = require('restify-clients');
console.log("starting...");
var client = restify.createJsonClient({url: 'http://localhost:'+process.env.PORT, version: '*'});
console.log("starting...2 ");
client.basicAuth('them', 'D4ED43C0-8BD6-4FE2-B358-7C0E230D11EF');
client.post('/create-user', { username: "me", password: "w0rd", provider: "local",
familyName: "GUD", givenName: "RG", middleName: "Ud", emails: [], photos: []},
(err, req, res, obj) => {
console.log("starting...4 ");
if(err) {
console.log("starting...5");
console.error(err.stack);
}
else {
console.log("starting...6");
console.log('Created ' + util.inspect(obj));
}
});
console.log("starting...3 ");
Here is the error I'm getting.. Surprisingly the server side code is able to insert the record into MongoDB, and yet I get this error..
InternalServerError: {}
at Object.createHttpErr (/Users/raviguduru/node-web-dev/chapter8/users/node_modules/restify-clients/lib/helpers/errors.js:91:26)
at ClientRequest.onResponse (/Users/raviguduru/node-web-dev/chapter8/users/node_modules/restify-clients/lib/HttpClient.js:309:26)
at Object.onceWrapper (events.js:300:26)
at ClientRequest.emit (events.js:210:5)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:583:27)
at HTTPParser.parserOnHeadersComplete (_http_common.js:115:17)
at Socket.socketOnData (_http_client.js:456:22)
at Socket.emit (events.js:210:5)
at addChunk (_stream_readable.js:309:12)
at readableAddChunk (_stream_readable.js:290:11)
Pls help.

This problem is solved now.. The internal server error comes when we have MongoDBClient calls not wrapped in try/catch blocks. After I included try/catch blocks, they went away.

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

sp-request : trying get file details from sharepoint returns ECONNREFUSED

I have the following code that successfully uploads test.sspkg to my sharepoint app catalog. Now I'm trying to use sp-request to prove that it's actually there.
But I'm getting an ECONNREFUSED error.
Error message
This shows the error:
[14:24:15] INFO: Checking if file (test.sppkg) is checked out
[14:24:15] INFO: File checkout type: 0
[14:24:17] Published file 1482ms
[14:24:17] And we're done...
trying to retrieve: https://mytenant.sharepoint.com/sites/JJTest/_api/web/GetFileByServerRelativeUrl(#FileUrl)/$value?#FileUrl='%2Fsites%2FJJTest%2FAppCatalog%2Ftest.sppkg'
errored out
{ GotError: connect ECONNREFUSED 127.0.0.1:443
at onError (/src/myplugins/node_modules/got/dist/source/request-as-event-emitter.js:140:29)
at ClientRequest.request.on.error (/src/myplugins/node_modules/got/dist/source/request-as-event-emitter.js:157:17)
at ClientRequest.emit (events.js:203:15)
at ClientRequest.EventEmitter.emit (domain.js:448:20)
at ClientRequest.origin.emit.args (/src/myplugins/node_modules/#szmarczak/http-timer/dist/source/index.js:43:20)
at TLSSocket.socketErrorListener (_http_client.js:401:9)
at TLSSocket.emit (events.js:198:13)
at TLSSocket.EventEmitter.emit (domain.js:448:20)
at emitErrorNT (internal/streams/destroy.js:91:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1107:14) name: 'RequestError', code: 'ECONNREFUSED' }
Package
This is the node package I'm using to call the SP API:
"dependencies": {
"sp-request": "^3.0.0"
}
Code:
const sprequest = require('sp-request');
await new Promise((resolve, reject) => {
gulp
.src(folderLocation)
.pipe(
spsync({
username: uname,
password: pwd,
site: siteCatalogUrl + "/",
libraryPath: catalogName,
publish: true,
verbose: true
}))
.on("finish", () => {
var spr = sprequest.create({ username: uname, password: pwd });
//https://mytenant.sharepoint.com/sites/JJTest/_api/web/getFileByServerRelativeUrl('/sites/JJTest/AppCatalog/test.sppkg')
var filepath = `${siteCatalogUrl}/_api/web/GetFileByServerRelativeUrl(#FileUrl)/$value?#FileUrl='${encodeURIComponent("/sites/JJTest/AppCatalog/test.sppkg")}'`;
console.log('trying to retrieve: ' + filepath);
var retrieveFileUrl = filepath;
spr.get(filepath, {
encoding:null
})
.then(data => {
expect(fileContent.equals(data.body)).is.true;
resolve();
})
.catch(data => {
console.log('errored out')
console.log(data)
reject();
});
resolve();
});
});
What I've tried:
I have tried just copying parts of the output from my console directly into the browser. Specifically, this is the output i get from my debug print statement:
trying to retrieve: https://mytenant.sharepoint.com/sites/JJTest/_api/web/GetFileByServerRelativeUrl/(#FileUrl)/$value?#FileUrl='%2Fsites%2FJJTest%2FAppCatalog%2Ftest.sppkg'
errored out
Pasting this:
https://mytenant.sharepoint.com/sites/JJTest/_api/web/GetFileByServerRelativeUrl('/sites/JJTest/AppCatalog/test.sppkg')
into a browser as the URL works. It returns the details of the file to me.
Can you tell me where I've gone wrong? maybe the syntax of substituting the #FileUrl?
I am using gulp version 3.9.1. And I just did a install latest of chai and sp-request.
But tried changing the specific versions to:
"sp-request": "^2.1.3"
"gulp": "^3.9.1",
"gulp-spsync-creds": "2.3.8",
"chai": "3.5.0"
And now, it's happy! it worked!

How can I get a stack trace into client code with the MongoDB Node.js driver?

I've noticed that MongoDB errors offer rather useless stack traces, pointing only within the driver's internals. The line of code in the client that triggered the error is not output:
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('...', { useNewUrlParser: true }, async (err, client) => {
try {
// some mongo client code...
// some more mongo client calls...
await client.db().collection('nonexistent').drop();
// yet more mongo client calls...
} catch (e) {
console.error(e);
}
client.close();
});
Here's the output from that:
MongoError: ns not found
at Connection.<anonymous> (/home/dandv/mongostack/node_modules/mongodb-core/lib/connection/pool.js:443:61)
at Connection.emit (events.js:200:13)
at processMessage (/home/dandv/mongostack/node_modules/mongodb-core/lib/connection/connection.js:364:10)
at TLSSocket.<anonymous> (/home/dandv/mongostack/node_modules/mongodb-core/lib/connection/connection.js:533:15)
at TLSSocket.emit (events.js:200:13)
at addChunk (_stream_readable.js:290:12)
at readableAddChunk (_stream_readable.js:271:11)
at TLSSocket.Readable.push (_stream_readable.js:226:10)
at TLSWrap.onStreamRead (internal/stream_base_commons.js:166:17) {
ok: 0,
errmsg: 'ns not found',
code: 26,
codeName: 'NamespaceNotFound',
name: 'MongoError',
[Symbol(mongoErrorContextSymbol)]: {}
}
If there's more than one mongo driver call in the try/catch block, it's impossible to tell which one generated the error.
Is there a way to have those stack traces lead up to client code?

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