The POST request encountered an error with status code 500 while being processed by the Express.js framework in the IncomingMessage

My current challenge involves creating a HTTP request for a CRUD application using JS. The aim is to add a new user account record to the Logins database. However, every time I attempt this request, it results in a 500 error:

To test this, I have written a simple script:

const axios = require("axios");

var http = axios.create({
    baseURL: "http://localhost:8080/",
    headers: {
        "Content-type": "application/json"
    }
});

class UserDataService {
    getAll(){
        return http.get("/users");
    }

    get(id){
        return http.get(`/users/${id}`);
    }

    create(data){
        return http.post("/users", data);
    }

    update(id, data){
        return http.put(`/users/${id}`, data);
    }

    delete(id){
        return http.delete(`/users/${id}`);
    }

    findByUsername(username){
        return http.get(`/users?username=${username}`);
    }

    authenticateLogin(data){
        console.log(data);
        return http.get("/login");
    }
}

function main(){
    const uds = new UserDataService();
    
    uds.create({
        username: "root",
        email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5c7dadac1f5d0dbc7dadb9bd6dad8">[email protected]</a>",
        password: "password"
    }).catch(err => {
        console.log(err);
    });
}

main();

This script then goes through users.routes.js:

router.post("/users", users.create);

And eventually reaches users.controller.js:

exports.create = (req, res) => {
    console.log("User being created");
    const user = {
        username: req.body.username,
        email: req.body.email,
        password: crypto.createHash("md5").update(req.body.password).digest("hex")
    };
    Users.create(user)
        .then(data => {
            res.send(data)
        })
        .catch(err => {
            res.status(500).send({
                message: err.message || "Error occurred when creating a user"
            })
        });
};

The error message received is as follows:

Error: Request failed with status code 500
    at createError (/home/amicharski/WebstormProjects/profrec/node_modules/axios/lib/core/createError.js:16:15)
    at settle (/home/amicharski/WebstormProjects/profrec/node_modules/axios/lib/core/settle.js:17:12)
    at IncomingMessage.handleStreamEnd (/home/amicharski/WebstormProjects/profrec/node_modules/axios/lib/adapters/http.js:293:11)
    at IncomingMessage.emit (node:events:402:35)
    at endReadableNT (node:internal/streams/readable:1343:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {

Answer №1

After implementing some changes, I successfully managed to authenticate the user on my website accessing their data in a secure manner.

function main(){
    const uds = new UserDataService();
    // http://localhost:8080'/api/users
    uds.create({
        "username": "admin",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b7d61616a4e6b606c717130677b76757c667874797caf7173">[email protected]</a>",
        "password": "12345"
    }).catch(err => {
        console.log(err);
    });
}

main();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing this JavaScript code not to run?

Help needed! I'm a student struggling to diagnose the issue in my code. Whenever I click the buttons, nothing happens at all. I've tried debugging by isolating each function, but still can't seem to figure it out. I've searched through ...

Leverage a nearby module with a local dependency

My current challenge involves integrating a local library into my project. I have been following two tutorials: how to create a library and how to consume a local library. Despite having a well-structured sample library with package.json and index.ts, I am ...

V5 Modal & jQuery: troubleshooting the spinner problem during loading of content

I'm working on displaying a spinner while loading modal content with the use of bootstrap v5 modal and jQuery. However, I encountered some issues in my example. The spinner does not display again after closing the modal; it only shows for the first t ...

Extension for Chrome that switches between active and inactive modes

I have been attempting to create an extension that can toggle the functionality of another specific extension on and off. Despite numerous attempts, I have not been able to find a solution that works effectively. Essentially, my extension displays a popup ...

I am encountering a JQuery syntax error while using Bootstrap 3 button-dropdown links

I'm trying to replicate the example found here in order to create a similar markup: <div class="btn-group"> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> ...

Is it possible to change the button class within a div while ensuring only the last one retains the change?

Here is a code snippet I'm using to switch between classes for buttons: $('button').on('click', function(){ var btn=$(this); if(btn.attr('class')=='tct-button'){ btn.removeClass('tct-button ...

Troubleshooting jQuery compatibility issues with Wordpress

Having some trouble implementing zclip on my Wordpress site to copy dynamically generated text. The code works fine as a standalone html page with embedded jquery, but it's not translating well to my Wordpress site. Even though I've placed the co ...

Calling Functions in JavaScript Through Events: A Beginner's Guide

As I dive into learning JavaScript, one thing that stumps me is figuring out how to call a function from an event. Currently, the only method I am familiar with involves using anonymous functions (as seen in my code example below), but I'm curious if ...

The Multer buffer returns as empty when utilizing memoryStorage

Currently, I am utilizing multer for managing uploaded files in an Express route. My goal is to convert the buffer into a base64 string for storage purposes. However, even when employing the memoryStorage option or if no options are specified (which should ...

Possibility for using navigator.GetUserMedia in Internet Explorer

How can I access a webcam through JavaScript/jQuery? I have successfully opened the webcam in Chrome and Mozilla, but the navigator.GetUserMedia feature does not work in Internet Explorer. Is there a way to achieve this with JavaScript or jQuery in IE? ...

When multiple forms have identical input IDs, only the first value is sent using Ajax

As I implement an ajax function to insert data into a database using a form and hidden input type, I encounter an issue where only the value from the first form on the page is being captured. Please see the following code: The Ajax function <script l ...

Encountering issues when adding information to a React table

Every time I try to submit data, I encounter an error message. Line 53: Expected an assignment or function call and instead saw an expression no-unused-expressions I am attempting to add user-submitted data onto a table as td elements. Could someon ...

Climbing the ladder of function chains, promises are making their

Here is the code structure that I've created to upload multiple files to a server using AJAX. After all the uploads are complete, it should perform a certain action. function uploadFiles(files){ const results = [] for (let i=0; i<files.length; i ...

What causes all the accordion panels to toggle simultaneously in a ReactJs application?

When I click on the + button in my accordion, all the sections open at once. What could be causing this issue? Here is my code: const questions = [ { id:1, question: 'What is React?', answer: 'React is a JavaS ...

Fixing blurry text on canvas caused by Arbor.js mouse event issues

Currently, I am utilizing arborjs in my project. The text within the canvas is created using fillText in html5. While everything functions correctly on a Retina display MacBook, the text appears blurry. To address this, I applied the following solution: v ...

Accessing a single Express app can result in the session being terminated in another app on the same server

On a single server machine, I have two Express 4.x applications running on different ports but sharing the same MongoDB instance. Each app uses its own database and session secret. When logging into either application A or B individually, everything works ...

Angular4 allows for the creation of a div that can horizontally scroll

Below is the HTML code I am working with: <div class="card-deck" fxLayout.xs="row" style="overflow: scroll; height:100%"> <md-card style="width:10rem" *ngFor="let make of filteredMakes" (click)="goToModels(make.niceName)" class=" ...

Transferring Information from React to MySQL

I'm currently developing a publishing application that requires communication between React and a MySQL database to exchange information. I am utilizing Express as my JavaScript server. Here is the code for the server: const express = require('e ...

The Express application fails to receive a response from a Mongodb query function

In my current project, I am implementing a simple API Key authentication system. The main goal is to validate the provided key against the user's input. There is a separate file containing a function that queries the database and returns either true/ ...

Can Express JS be utilized with an MS Access database?

Can a Microsoft Access database (.accdb) be utilized as the back-end for an express js application? I have attempted various packages for connecting it without success. Are there alternative methods to connect an MS Access db with an express REST API? ...