Storing POST Request Data in Express

I want to use a single API endpoint for both GET and POST requests.

My goal is as follows:

  1. Send multiple POST requests to /api/users with data like: {'id': 2, is_valid: 'true'}
  2. Retrieve this data by fetching the same API URL later on and display it in my application.

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const port = 5000;

const jsonParser = bodyParser.json();


app.all('/api/users', jsonParser, (req, res) => {
    const users = [
        {id: '1', is_valid: false}
    ];

    users.push(req.body);

    res.json(users);
});

However, whenever I fetch this endpoint, it always shows the original users array. The data I added to my array never gets saved.

Answer №1

Did you attempt relocating

let animals = [
    {type: 'Dog', has_tail: true}
];

outside of the function (e.g. a minimum of two lines before)?

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

How can I create an asynchronous route in AngularJS?

I implemented route and ngView to display dynamic content, however I received a warning message: The use of Synchronous XMLHttpRequest on the main thread is deprecated due to its negative impact on user experience. For more assistance, please refer to ...

The ajax success() function is failing to function properly when attempting to make a call

The button's onClick() event is not navigating anywhere. There seems to be an issue with the success() function of the ajax call. Unfortunately, I am new to this and unable to pinpoint the problem. var currentAuthor=""; var currentQuote=""; $(documen ...

What is the best way to apply a hover effect to a specific element?

Within my CSS stylesheet, I've defined the following: li.sort:hover {color: #F00;} All of my list items with the 'sort' class work as intended when the Document Object Model (DOM) is rendered. However, if I dynamically create a brand new ...

What is the best way to retrieve a default property from a JavaScript literal object?

In the following example, a JS object is created: var obj = { key1 : {on:'value1', off:'value2'}, key2 : {on:'value3', off:'value4'} } Is there a clever method to automatically retrieve the default valu ...

Adjusting the dimensions of the cropper for optimal image cropping

I am currently working on integrating an image cropper component into my project, using the react-cropper package. However, I am facing a challenge in defining a fixed width and height for the cropper box such as "width:200px; height:300px;" impo ...

Why does the return value of a function in Node.js and JavaScript sometimes appear as undefined?

I am completely stumped by this issue. I've been trying to figure it out, but so far, no luck.. this is the code snippet function part1(sql, controltime, headers_view, results_view, tmp){ var timerName = "QueryTime"; var request = ne ...

In the middleware, the request body is empty, but in the controller, it contains content

Below is my server.js file: import express from "express"; import mongoose from "mongoose"; import productRouter from "./routers/productRouter.js"; import dotenv from "dotenv"; dotenv.config(); const app = expres ...

altering the color of various spans consecutively

I am looking to create a text effect where each alphabet changes color in a wave-like pattern, starting from the left. I have assigned each alphabet a span with classes like span0, span1, and so on. To change the color, I used the following code: for (var ...

Unlocking the Controller Action: Navigating from a Component Controller in Ember

I am currently trying to enhance the functionality of an Ember component. The specific component I am working on is located here: app / templates / programmers.hbs {{echo-hlabel-tf id= "id-test-hlabel" class="class-test-hlabel-mio" label="Horiz ...

Finding the index of a column based on a continuous sequence of values can be achieved by following these

Consider this sequence of numbers representing components on a page: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 Every set of 3 numbers makes up a page, with indexing restarting for each new page. Essentially, it follo ...

Multiple ngFor loops causing only the final item to be displayed in the inner loop

Can someone assist with my code where I loop through firebase RTDB reference to retrieve a list and then use those results in a subsequent firestore query? The console logs the correct data, but my code only displays the last item in the loop inside ngFor. ...

When trying to view the page source in Next.js, the page contents do not display

I made the decision to switch my project from CRA to nextjs primarily for SEO purposes. With Server Side Rendering, the client receives a complete HTML page as a response. However, when I check the source of my landing page, all I see is <div id="__next ...

Generating a collection of objects using arrays of deeply nested objects

I am currently working on generating an array of objects from another array of objects that have nested arrays. The goal is to substitute the nested arrays with the key name followed by a dot. For instance: const data = [ id: 5, name: "Something" ...

Error encountered while retrieving data from Firebase and storing it in an array within an IONIC application

I am currently working on a function that retrieves data from Firebase's real-time database and stores it in an array for mapping in React. However, I am encountering a TypeScript error that I'm having trouble resolving. The error message reads ...

Utilize a singular ng-model for efficiently filtering and presenting filtered data

Recently, I encountered an issue with a HTML select element that is used to sort a list. The code for the select element looks like this: <select ng-init="sortMethod=sortMethods[0]" ng-model="sortMethod"> <option ng-repeat="sortMethod in sortMe ...

How can I transfer form data to a PHP variable using an AJAX request?

Encountering some difficulties, any insights? I have included only the necessary parts of the code. Essentially, I have an HTML form where I aim to extract the value from a field before submission, trigger an ajax call, and fill in another field. It seems ...

Ensure that the input box expands to occupy the entire HTML page

After reviewing numerous pages and questions related to this topic, I have located the correct solution but am struggling to implement it. My goal is to achieve a similar outcome to the second question, but I'm having difficulty figuring out how to do ...

Fetching content-type in React code locally executed

I am a beginner in front end development and I need help with setting the "application/json" content-type and gzip content-encoding in the fetch call for my locally run React code. Can anyone provide guidance on this? const data = await fetch(url, { ...

There's just something really irritating me about that Facebook Timer feature

Have you ever noticed the timers constantly updating on Facebook? Whether it's an Ajax Request triggered by a timer or a client-side timer, there are numerous timers being used. Does this affect the performance of the website, and is there something c ...

Obtain a string of characters from different words

I have been trying to come up with a unique code based on the input provided. Input = "ABC DEF GHI" The generated code would look like, "ADG" (first letter of each word) and if that is taken, then "ABDG" (first two letters o ...