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

Unable to locate FFmpeg on the root server for Discord JS v13

After setting up my DiscordJS Bot on a new rootserver, I transferred all the files and launched the bot. Everything seemed to be working fine until I tried to run a command that involved the bot joining a voice channel and playing audio. At this point, an ...

Include chosen select option in Jquery form submission

Facing some challenges with a section of my code. Essentially, new elements are dynamically added to the page using .html() and ajax response. You can see an example of the added elements in the code. Since the elements were inserted into the page using . ...

Utilizing ElementRef in Angular 4 to close dropdown when clicking outside of it

I recently came across this helpful tutorial, but I'm having trouble grasping how it actually functions. Here's the code snippet I've incorporated into my TypeScript file: @Component({ host: { '(document:click)': 'onOuts ...

Tips for maintaining i18n locale slugs and ensuring i18n consistency when reloading in Next.js

I'm currently utilizing next-translate. The default recognition of my routes is as follows: /about <--- /de/about /es/about However, I would like to set a specific locale for all paths: /en/about <--- /de/about /es/about Below is ...

An uncomplicated broadcasting and receiving method utilizing an event emitter

This code is from chapter 3, example 11 of the book Node.JS in Action, found on page 52. var events = require('events'); var net = require('net'); var channel = new events.EventEmitter(); channel.clients = {}; channel.subscriptions = ...

Show a variety of pictures in a random arrangement?

Looking for some help here! I'm trying to shuffle my images in a random order each time the page is refreshed. It's like a game of musical chairs but with pictures! Does anyone know how to achieve this? I've done some searching, but haven& ...

`Express 4 with beautiful locals.pretty`

Is there a way to send nicely formatted HTML using Express 4? I need to know how to properly use app.locals.pretty with Express 4. The old syntax doesn't seem to be working: app.locals.pretty = true; Here is the full code block: app.set('port& ...

"Upon completing an AJAX file upload, both $_POST and $_FILES arrays are found

Recently, I've delved into the realm of web development and encountered a hurdle with ajax file uploading... My current setup involves two HTML input fields: one for files and another for a button. <input type="file" name="Frame" id=" ...

Automatically redirect users on page refresh using jQuery

I am attempting to use jQuery to detect when the user refreshes the page in order to redirect, but I can't seem to get it working. Can someone help me figure out what is wrong with this code? <?php include 'instagram.php'; ?> <! ...

Attempting to send headers to the client after they have already been set - Node.js

Every time I try to submit the form, I keep getting an error message that says "Cannot set headers after they are sent to the client". I have tried redoing everything but still face the same issue. Here is the code for the form: const loader = document.qu ...

Initiating a YouTube video with a click on its thumbnail image - a jQuery tutorial

I am currently working on code that successfully displays YouTube videos. However, I would like the video to start playing when the cover image is clicked. How can I achieve this functionality? Thank you for your help! <div id="video" style="display: ...

Adjust properties based on screen size with server-side rendering compatibility

I'm currently using the alpha branch of material-ui@v5. At the moment, I have developed a custom Timeline component that functions like this: const CustomTimeline = () => { const mdDown = useMediaQuery(theme => theme.breakpoints.down("md")); ...

Modifying an element in an array while preserving its original position

Currently, I am working on updating the state based on new information passed through response.payload. Here is my existing code snippet: if(response.events.includes('databases.*.collections.*.documents.*.update')) { setMemos(prevState => pre ...

Is it possible to calculate a variable within a dataset using existing data as a reference point?

Is there a way to dynamically compute some of the data variables in a Vue instance by referencing other variables and tracking their changes? new Vue({ el: '#root', data: { x: 1, y: x + 1 } }) <script src="https://cdnjs.cloudf ...

Prevent user input in HTML

Currently, I am working on creating the 8 puzzle box game using JavaScript and jQuery Mobile. The boxes have been set up with <input readonly></input> tags and placed within a 9x9 table. However, an issue arises when attempting to move a box ...

Update the displayed number on the input field as a German-formatted value whenever there is a change in the input, all while maintaining

In German decimal numbers, a decimal comma is used. When formatting, periods are also used for grouping digits. For example, the number 10000.45 would be formatted as 10.000,45. I am looking to create an input field (numeric or text) where users can input ...

What are the reasons for a jQuery function to run in a selective manner?

There seems to be some inconsistency in the behavior of this incomplete script that I'm trying to debug. The issue arises when I click off an item, as sometimes the $(editObj).removeAttr('style'); line of code executes and other times it doe ...

Django issue: A Tuple or struct_time argument is necessary

Currently, I am developing a code that deals with 2 variables - showdate and viewtype. Both of these variables are transferred via JavaScript using the POST method. viewtype = send an srt showdate = send a date from javascript Within this code snippet, ...

Using PHP to read an image blob file from an SVG

Currently, I am utilizing the Raphael JS library on the client-side to generate a chart in SVG format. However, my goal is to make this chart downloadable, which poses a challenge since SVG does not natively support this feature. Initially, I attempted to ...

Ways to manage properties that are non-existent

Whenever vm8 encounters a property that doesn't exist, it will display an error message like this: Cannot read property 'value' of null. For example, when passing an id that doesn't exist: var pass = document.getElementById('pass ...