Retrieve the request body in Node.js Express server-side code in order to receive an array passed from the front end

I am facing an issue where I need to save a user's array to mongo. When the data passes through the bridge and reaches the posts, it appears as a strange object with string versions of its indices. I am attempting to convert it back into a normal array so that it can be saved to mongo database. However, the process is very delicate and keeps throwing errors. Is there a specific parsing operation that I might be overlooking?

bridge:

static storeUsers(users){
    try{
        let command = 'storeUsers';
        return axios.post(url + command, {
            params: users
        });
    } catch(err){
        reject(err);
    }
}

posts:

router.post('/storeUsers', async (req, res) => {
    let collection = await loadCollection('users');
    let userArray = req.body.params.toArray(); // this line causes issues
    await collection.insertMany(
        userArray
    );
        res.status(201).send();
});

Answer №1

function storeUsers(users){
    try{
        let action = 'storeUsers';
        return axios.post(path + action, {
            data: JSON.stringify(users) // convert users to a string using JSON.stringify
        });
    } catch(error){
        reject(error);
    }
}
router.post('/saveData', async (request, response) => {
    let database = await loadDatabase('users');
    let userArray = JSON.parse(request.body.data) // parse data
    await database.insertMany(
        userArray
    );
        response.status(201).send();
});

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

Exploring the process of uploading images to MongoDB buffers using React on the client side

I am currently utilizing multer for file uploads const upload = multer({ limits: { fileSize: 1000000 }, fileFilter(req, file, cb) { if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) { return cb(new Error( ...

Stop the event propagation when the back button is clicked

While utilizing ons-navigator, I am looking to customize the function of a particular element at a certain stage. Employing the onClick handler has allowed me to successfully trigger this function. However, upon exiting the onClick handler, the navigator ...

Tips for achieving proper styling and formatting of elements in jQuery UI

I've encountered an issue when trying to use jQuery UI after downloading it multiple times. In the examples provided with the download, the UI elements appear perfectly formatted, but when I implement them on my own pages, the styles and formatting ge ...

Choose the highest N rows from every category

My blog platform utilizes MongoDB for storing user-created blogs. Each blog entry is stored in a collection called 'entries', with the document structure as shown below: { 'blog_id':xxx, 'timestamp':xxx, 'title&apo ...

Initially receiving a 404 error, the GCloud AppEngine nodejs application eventually becomes successful with subsequent requests

While deploying a Node.js server (GraphQL) application on GCloud AppEngine standard environment, I am facing an issue where the first requests fail occasionally, but the subsequent ones (within 5 seconds) work fine. The configuration I am using is as follo ...

I am unable to implement code coverage for Cypress in Debian at the moment

Having trouble obtaining code coverage results using Cypress in my Virtual Machine (Debian Bullseye), but no issues when I run the same project on my Windows machine. On Linux, the code coverage shows up as: Click here to view Index.html inside lcov-repor ...

Verification of JQuery UI Dialog Prompt using the Enter key

I have attempted the methods recommended in a stack answer but to no avail: Submit jQuery UI dialog on <Enter> There seems to be an issue with my code. Upon logging in, a disclaimer appears to notify users that the content within the site is confid ...

Unable to execute a GET request using the Fetch API on Django REST Framework results in receiving an HTTP 304 error code

When attempting a GET request with the Fetch API (Node Fetch) module against a Django REST API, I am encountering a 304 error. I am unsure of how to resolve this issue as it seems to be related to requesting the same data repeatedly. Is there no way around ...

Exploring the Angular framework: Combining form requirements and controllers in directives' link functions

In my coding journey, I have developed a powerful directive known as formNavHandler. This directive plays a crucial role in handling dirty checking and smooth navigation between different pages. The functionality of formNavHandler heavily relies on the exp ...

What methods are available to transfer a variable from one component to another in React?

In my React app, I have a form component that interacts with a PostgreSQL database to send data. Here is the script for my form: import bodyParser from 'body-parser'; import React, { Fragment, useState } from 'react'; import RatingStar ...

Navigating through segments of an array in javascript

Within my condensed array, I have omitted most of the input data to demonstrate a particular task. For illustrative purposes, here is an extensive example showcasing the elements: storyArray=["#C1", "String showing first message", "String displaying secon ...

"Enhance your website with dynamic uploader forms and AJAX scripts - Railscast #383 shows you

I've successfully implemented the uploader functionality from Railscast #383, but I'm wondering if it's possible to dynamically add and remove the uploader link using ajax? Additionally, I'd need to include the "service" instance id wh ...

There is no result being returned by Model.findOne()

Why does Model.findOne() return null even when a valid collection is present in the respective Model? app.post("/fleetManagement", (req, res) => { const requestedDriverID = req.body.driverId; console.log(requestedDriver ...

Obtaining specific data from the forEach iteration, post-click event with JavaScript

Trying to access the value from a Tree-structured Array of Objects stored in Local Storage, Created a function that retrieves values from local storage using forEach and displays them on the screen. Clicking on the Yes/No button triggers the same functio ...

What impact do include statements have on performance?

As I develop a node server, utilizing express and ejs as the templating engine, I've noticed that some of my .ejs files contain 7 to 8 include statements for nested partials. I'm curious whether this approach is resource-intensive or if it won&ap ...

The image upload failed: the server could not locate the requested URL

I am completely new to working with Flask, and I'm currently in the process of creating a basic image uploading application. After comparing my code with various tutorials on how to build similar apps, it seems like everything is in place. However, w ...

What is the best way to manage a significant volume of "business" data or objects within my JavaScript project?

I specialize in working with AngularJs and have a factory that provides services related to buildings. I am managing a large number of buildings (around 50-60) with multiple properties and sub-properties associated with each one (approximately 15-20, some ...

Efficient Techniques for Deleting Rows in a Dynamic JavaScript Table

I'm facing an issue where I want to remove each line added by the user, one by one. However, my current program is removing all the rows from the table instead of just one at a time. The objective is to allow the user to remove a specific row if they ...

The scrolling speed of my news div is currently slow, and I am looking to increase its

This is the news div with bottom to top scrolling, but it is slow to start scrolling. I want to increase the speed. The current behavior is the div appears from the y-axis of the system, but I want it to start exactly where I define. The scrolling div is ...

In Vue, when utilizing Firestore, the .where method doesn't seem to be returning any results even though they do exist in

As a newcomer to Firestore, I'm working on a query to display chat messages that update in real-time when new ones appear. However, I'm facing an issue where only messages from the current user's school should be visible. If I omit the .wher ...