Is it possible to send back the posted data using res.send after making a post request

I am currently facing a challenge with my post route, where I receive an array of strings from req.body. This array is then used to query my local MySQL database multiple times in order to retrieve specific data that I need to send back to the client (react) and store in state.

The issue arises when trying to store this data in an array to be sent successfully via the res.send or res.json method.

I suspect that the problem might be related to handling scope in a different way, but I am at a loss on how to solve it.

I have attempted to move the declaration of the original array variable around, but even with res.send(aisleArr), I only end up receiving an empty array.

I also tried omitting the declaration of 'aisleArr' before using the push method, hoping it would create a global aisleArr object, but that did not work either.

router.post('/complete', (req, res) => {

  const list = req.body;

  let aisleArr = [];

  list.map(item =>
    db.item.findAll({
      where: {'$item.name$': item}
      })
      .then(data => data.map( data => 
        db.aisle.findAll({
          where: {'$aisle.id$': data.dataValues.aisleId, '$aisle.storeId$': 2}
        }).then( result => { 

          if(result[0]){
            aisleArr.push(result[0].name)
          }else{
            console.log('no match')}})
        ) 
      )
    )
res.send(aisleArr)
});

Upon completion of res.send, the client console only shows an empty array being received.

Answer №1

It seems essential to ensure the completion of the map iterator before sending the value. While the return values are linked with promises, the assignment to aisleArr may not be chained properly and res.send might be triggered before the iterator finishes its task. Using async/await could offer a simpler way to guarantee that the assignment is finalized before proceeding.

Here's an illustration:

router.post('/complete', async (req, res) => {

  const list = req.body;

  const aisleArr = await list.map(item =>
    db.item.findAll({
      where: {'$item.name$': item}
    })
    .then(data =>
      data.map(newData =>
        db.aisle.findAll({
          where: {'$aisle.id$': newData.dataValues.aisleId, '$aisle.storeId$': 2}
        })
        .then(result => {
          if (result[0].name) {
            return result[0].name;
          } else {
            console.log('no match');
          }
        });
      );
    );
  ).filter(aisle => aisle);
  // the filter at the end will remove null values
  // (when nothing is returned from the last call to .then)

  res.send(aisleArr);
});

I haven't tested this code, so it might need some adjustments, but I believe it provides a good starting point. The key thing to keep in mind is ensuring that the map operation is completed before calling res.send. Adding more console.logs could help confirm if this is indeed the issue.

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

Leverage shared techniques and libraries across two different projects

I have a NodeJS project set up on Firebase cloud functions, with our backend service (ExpressJS) as an HTTP function and some cron functions. The project structure looks like this: /project (the main directory for all cloud functions) - package.json ...

Utilize Express and EJS to dynamically showcase an image on a webpage

In my collection, I have various URLs for images. I extract the specific URL I need and want to pass it to a jade template like this: app.get('/',function(req,res){ mongoDB.getUsedHomePageOne(function(err, result){ if(!err){ ...

How is it possible that rows are still being added to the table even when the indexOf function returns 0?

This jQuery script allows for adding new rows to a table when a button is clicked, but only if the id value has not already been added. var addedFacts = []; $('#btnAddFact').on("click", function (e) { e.preventDefault(); // no_fact and ...

Using Rails AJAX to dynamically load partials without the need to submit

Imagine creating a dynamic page layout with two interactive columns: | Design Your Pizza Form | Suggested Pizzas | As you customize your pizza using the form in the left column, the right column will start suggesting various types of pizzas based on your ...

Tips for clearing form validation errors on dynamically populated fields using data stored in localStorage

Currently, I have a form that requires validation. The desired behavior is for the form to display an error message ("this is required") and disable the submit button if any of the input fields are left empty. The validation works correctly as intended, bu ...

Click the edit button to access the options in the material table

https://i.stack.imgur.com/Inyow.png Currently, I am utilizing Material Table within Reactjs to display the table Data. However, I have encountered a hurdle where I need to alter state upon clicking on the edit option/icon. My objective is not to modify th ...

Switch out everything except for the initial one

Can all instances be replaced except for the first one? For example, 123.45.67..89.0 should turn into 123.4567890. Edit: Specifically seeking a regex solution. I am aware of how to achieve it through concatenation or using the index. ...

Unable to locate resource for passport authentication middleware

Here is a snippet of code that I am currently working with: passport.use(new LocalStrategy({ usernameField: 'emailAddress', passwordField: 'password', passReqToCallback: true }, function(req,username, password, next) { var re ...

Lagging application utilizing LocalStorage alongside AngularJS

I have developed an application that organizes, compares, filters, and generates statistics from a dataset. The app is designed to function offline since some users may not always have internet access. However, I am encountering a problem where the app be ...

My PHP errors and success messages are not being displayed properly after an AJAX success

After making an AJAX call to submit a form, I would like to display either the PHP success message or error message upon completion. This is my current AJAX success function: success: function (data) { resultSuccess = $(data).find("#success") ...

How come my query object is having trouble utilizing the _id field correctly?

I am currently in the process of developing a Node.js web API using Express and MongoDB. The main challenge I am facing is dynamically parsing the req.query object (which stores and parses querystrings in Express) from a GET request, and then updating an ...

What is the best way to utilize a single AngularJS 1.5 component multiple times within a single view?

While working on a project using AngularJS 1.5's new components, I encountered an issue with widget isolation. It seems that when I use the same widget multiple times, they end up sharing their controller or scope. I was under the impression that comp ...

Error: The "render" method is not available for the IncomingMessage object

While working on a basic application using node.js and express, everything seems to be in order except for this error that keeps popping up: res.render("aggregatedCostList",{ ^ TypeError: Object #<IncomingMessage> has no method 'render&ap ...

Update information in angularjs

Currently, I am in the process of setting up a mailing application. In order to capture user activity when they first load the page, I am performing a POST request to the database with the userId and date information. Upon successful completion of the POS ...

Customize HTML content before using it as a static server

Before implementing expressApp.use(express.static(path.join(__dirname, '/../frontend/dist')));, I need to make changes to the HTML code. The task at hand involves inserting meta tags in two separate middleware functions. I have managed to devise ...

Utilizing Jquery for independently blinking text counters

Whenever the user presses a button, a message is created and blinks 5 times. However, each time the button is pressed, all previous messages also blink along with the new one. The goal is to make only the new message blink individually 5 times upon each bu ...

Creating a Restful API without relying on frontend javascript can be achieved by implementing server-side

I've been on the hunt for a guide to create a RESTful API without relying on frontend JavaScript, but I haven't had any luck so far. As someone new to Javascript and web development, I've been working on tutorials and little projects to fami ...

Tips on submitting an Array from a Textarea to mongoDB

I have a question regarding posting an array of serial numbers. When I try to post the serial numbers added in the textarea, they are posted as a single string. Here is my form: <form class="" id="serialsForm" action="/serialsnew" method="post"> &l ...

Is there a way to bring in data from a .d.ts file into a .js file that shares its name?

I am in the process of writing JavaScript code and I want to ensure type safety using TypeScript with JSDoc. Since it's more convenient to define types in TypeScript, my intention was to place the type definitions in a .d.ts file alongside my .js fil ...

Navigate to a different page and automatically launch a few lightbox pop-ups

I have a website address: www.example.com/test123 When users visit this page, it redirects to: <% response.redirect "http://www.example.com/index.asp?test=true" %> What I want is for the page to open a lightbox with another file inside when redire ...