skip to Main Content

When I send an API request using Hoppscotch, I get an error in my terminal and status code: 500 on hoppscotch. I am not able to rectify the problem. I am attaching my code below.

var mongodb = require('mongodb');
var ObjectID = mongodb.ObjectId;
var crypto = require('crypto');
var express = require('express');
var bodyParser = require('body-parser');
const exp = require('constants');

var genRandomString = function (length) {
    return crypto.randomBytes(Math.ceil(length / 2))
        .toString('hex')
        .slice(0, length);
};

var sha512 = function (password, salt) {
    var hash = crypto.createHmac('sha512', salt);
    hash.update(password);
    var value = hash.digest('hex');
    return {
        salt: salt,
        passwordHash: value
    };
};

function saltHashPassword(userPassword) {
    var salt = genRandomString(16);
    var passwordData = sha512(userPassword, salt);
    return passwordData;
}

function checkHashPassword(userPassword, salt) {
    var passwordData = sha512(userPassword, salt);
    return passwordData;
}

var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

const mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/hwmDatabase')
    .then(() => {
        app.post('/register', (request, response, next) => {
            var post_data = request.body;

            var plaint_password = post_data.password;
            var hash_data = saltHashPassword(plaint_password);

            var password = hash_data.passwordHash;
            var salt = hash_data.salt;

            var name = post_data.name;
            var email = post_data.email;

            var insertJson = {
                'email': email,
                'password': password,
                'salt': salt,
                'name': name
            };

            var db = client.db('hwmDatabase');

            db.collection('user')
                .find({ 'email': email }).count(function (err, number) {
                    if (number != 0) {
                        response.json('Email already exists');
                        console.log('Email already exists');
                    }
                    else {
                        db.collection('user')
                            .insertOne(insertJson, function (error, res) {
                                response.json('Registration successful');
                                console.log('Registration successful');
                            })
                    }
                })
        });

        app.post('/login', (request, response, next) => {
            var post_data = request.body;

            var email = post_data.email;
            var userPassword = post_data.password;

            var db = client.db('hwmDatabase');

            db.collection('user')
                .find({ 'email': email }).count(function (err, number) {
                    if (number == 0) {
                        response.json('Email not exists');
                        console.log('Email not exists');
                    }
                    else {
                        db.collection('user')
                            .findOne({ 'email': email }, function (err, user) {
                                var salt = user.salt;
                                var hashed_password = checkHashPassword(userPassword, salt).passwordHash;
                                var encrypted_password = user.password;

                                if (hashed_password == encrypted_password) {
                                    response.json('Login success');
                                    console.log('Login success');
                                }
                                else {
                                    response.json('Wrong password');
                                    console.log('Wrong password');
                                }
                            })
                    }
                })
        });

        console.log("Connection Open!")

        app.listen(3000, () => {
            console.log("APP IS LISTENING ON PORT 3000")
        })
    })
    .catch(err => {
        console.log("Error lmao")

        console.log(err)
    })

The package.json file is attached below:

{
  "name": "hwm_nodejs_mongodb",
  "version": "1.0.0",
  "description": "hwm backend",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "Underdogs_United",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.20.2",
    "crypto": "^1.0.1",
    "express": "^4.18.2",
    "mongodb": "^6.3.0",
    "mongoose": "^8.0.1"
  }
}

This code is part of a task which was given to us (I am part of a team). I have to create a database using MongoDB using node.js as server. I used express as I am comfortable with it.
When I used an API testing tool to see if i can send data to my database, I was unable to do so. It showed status code:500 and rather than getting a JSON file, it got an HTML file, which is an error.
The error it showed on the terminal is as follows:
Connection Open!
APP IS LISTENING ON PORT 3000
TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined
at new NodeError (node:internal/errors:406:5)
at Hmac.update (node:internal/crypto/hash:104:11)
at sha512 (C:UsersBS JaglanDocumentshwm_nodeJS_mongoDBindex.js:16:10)
at saltHashPassword (C:UsersBS JaglanDocumentshwm_nodeJS_mongoDBindex.js:26:24)
at C:UsersBS JaglanDocumentshwm_nodeJS_mongoDBindex.js:46:29
at Layer.handle [as handle_request] (C:UsersBS JaglanDocumentshwm_nodeJS_mongoDBnode_modulesexpresslibrouterlayer.js:95:5)
at next (C:UsersBS JaglanDocumentshwm_nodeJS_mongoDBnode_modulesexpresslibrouterroute.js:144:13)
at Route.dispatch (C:UsersBS JaglanDocumentshwm_nodeJS_mongoDBnode_modulesexpresslibrouterroute.js:114:3)
at Layer.handle [as handle_request] (C:UsersBS JaglanDocumentshwm_nodeJS_mongoDBnode_modulesexpresslibrouterlayer.js:95:5)
at C:UsersBS JaglanDocumentshwm_nodeJS_mongoDBnode_modulesexpresslibrouterindex.js:284:15

2

Answers


  1. The first thing I would do once encountering such a bug is test an online MongoDB provider —e.g. MongoDB Atlas. Another option, if I am offline, is to change the IP – the mongodb://127.0.0.1:27017/hwmDatabase in your case – with the usual localhost:27017 connection – mongodb://localhost:27017/hwmDatabase in your situation. So, if you are offline, try to make sure that MongoDB is working on your device. On Windows, you need to search for Services and ensure that MongoDB Service is running. I don’t know what to do with Mac or Linux, so here are some useful links for all! Mostly, care for the community edition unless you know what you are doing:https://www.mongodb.com/docs/manual/installation/

    If that didn’t work, then start slowly with a new js file and try to make the connection at the beginning. Mostly it will work as you only have very few lines of code. Then progress slowly and log things to the console so that you can see where the bug is happening. If you couldn’t make the connection from the beginning, then take a look at the links below.
    https://sparkbyexamples.com/mongodb/node-js-using-express-with-mongodb/
    https://medium.com/featurepreneur/connect-mongodb-database-to-express-server-step-by-step-53e548bb4967

    Login or Signup to reply.
  2. Based on the error stack trace it looks like the password value you are sending to the sha512 function is not a string but some other type of object. It does not appear to be a connection issue with mongodb. See here for more info on the crypto hash.update() function.
    Looking closely at the error message you received points to this:

    TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type
    string or an instance of Buffer, TypedArray, or DataView

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search