The Express API will only provide the initial key-value pair of an object in the response

I'm working on fetching nested data objects. Although I can successfully retrieve the object data in the console, I encounter an issue when attempting to access this data using return res.json(imageObject). Instead of retrieving all key-value pairs of the object, only the first pair is returned. The error message displayed in the console reads:

UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
. The console data looks like this: { bigImage: 'https://url.com' }

router.get("/", async(req, res) => {
  //...fetching data
  if (mediaData.type === "type1") {
    let allData = await mediaData.media;

    allData.map(async(Data) => {
      if (Data.imageType === "big") {
        let bigImage = await Data.url;
        let imageObject = {
          bigImage
        };
        console.log(imageObject);
        return res.json(imageObject);
      }
    });
  }
});

Answer №1

The utilization of res within a .map function will trigger it for each element in the array being iterated.

It is essential to avoid this practice as you should only use res once per req, considering that you are responding to the browser. Reusing it multiple times will lead to an error indicating that it has already been utilized and a response has already been sent.

To resolve this issue, ensure that res is used only once and not within a map function.

Furthermore, utilizing .map in this context is unnecessary since you are not interested in the generated output. It would be more appropriate to utilize forEach or, even better, a for loop (which can be broken based on a condition).

Answer №2

The best approach is to utilize the for..of loop.

This will halt the function's execution upon encountering the return statement.

router.get("/", async(req, res) => {
  //...fetch data
  if (mediaData.type === "type1") {
    let allData = await mediaData.media;

    let pendingResult = allData.filter(data => data.imageType === "big").map(async item => {
       let bigImage = await item.url;
       return { bigImage }
    });
    
    let result = await Promise.all(pendingResult);

    res.json(result);
  }
});

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

Tips for documenting curried functions using Js docs

I'm encountering issues while trying to use Js docs for generating static documentation of my project. When attempting to run the js doc command, I am faced with numerous parse errors specifically in areas where I have curried functions. Strangely, my ...

When incorporating `io.sockets.emit` within the router, what happens if the socket connection has not been fully established beforehand?

Utilizing io.sockets.emit in the router as shown below: db.SomeModel.find({}, function(err, modelDate) { io.sockets.emit('eventName', modelData); } ); If a socket takes around 10 seconds to be established (just an example), a ...

Linking Google Form Data to a MongoDB Database

Looking to integrate Google form with mongodb for data collection. Need help setting it up using NodeJs. Any advice on how to approach this? ...

I'm encountering an unfamiliar error within my Discord.js bot, and I'm unsure of both its cause and the appropriate solution. Additionally, I'm unsure which specific file

I'm facing a recurring issue with my bot terminal. It's been causing me trouble for the past four days, functioning intermittently without any pattern. I'm struggling to track down the specific file where this error is originating from. Any ...

Is there a way to interact with specific locations on an image by clicking in JavaScript?

https://i.stack.imgur.com/gTiMi.png This image shows a keypad with coordinates for each number. I am able to identify the coordinates, but I am struggling to click on a specific coordinate within the image using JavaScript. Can someone assist me in achiev ...

Allowing SVGs to be clickable without disrupting the functionality of YouTube videos

I'm experiencing an issue with the overlapping of the svg and YouTube elements. If you hover your mouse over, just to the right of the svg and click, instead of opening the video, it redirects you back to the previous page. Clicking on the area betw ...

When imported, Node / JS instantly generates a new instance

Is there a way to instantiate a class without importing it first and using new afterward? Instead of var mainClass = require('../dist/main'); // has "class Main { ... }" var mainInstance = new mainClass(); I am looking for something like var ...

The drop-down menu selection is non-functional on mobile and iPad devices when using Bootstrap

<div class="panel panel-default"> <select> <option value="B3">B3</option> <option value="B4">B4</option> <option value="B5">B5</option> & ...

The ng-model-options in Angular 2 is set to "updateOn: 'change blur'"

Currently working with angular 2, I am seeking a solution to modify the behavior of ngModel upon Enter key press. In angular 1.X, we utilized ng-model-options="{updateOn: 'change blur'}". How can this be achieved in angular 2? For reference, her ...

Unveil the Expressjs middleware within the API Client

I am currently developing a Nodejs API Client with the following simple form: //client.js function Client (appId, token) { if (!(this instanceof Client)) { return new Client(appId, token); } this._appId = appId; this._token = tok ...

Is there a way to calculate the total of form field values in Vue.js?

I am currently working on a project that involves calculating the total sum of 5 input fields. I have set up data fields and v-model for each field, and in my computed section I am attempting to calculate the sum. <input type="text" class="form-contro ...

Learn how Angular 2 allows you to easily add multiple classes using the [class.className] binding

One way to add a single class is by using this syntax: [class.loading-state]="loading" But what if you want to add multiple classes? For example, if loading is true, you want to add the classes "loading-state" and "my-class". Is there a way to achieve t ...

Leverage the power of Vue Nuxt Auth to activate authentication middleware on a route-by-route

Is there a way to implement auth middleware for individual routes using Class Components? How can I achieve the same functionality as this: <script> export default { middleware: 'auth' } </script> The following method does n ...

Guide to updating passwords with passport-local-mongoose

After successfully importing the passport-local-mongoose to my code and being able to register and log in users, I now face the challenge of changing the password for a specific user. How can I achieve this? According to the documentation of passport-local ...

Analyzing a CSV file and executing asynchronous operations on specific columns with the help of ajax requests

I possess a CSV file that contains placement links and target links formatted as follows: CSV Example [placement url],[target url] [placement url],[target url] [placement url],[target url] My objective is to parse the CSV file line by line using JavaScri ...

PassportJS OAuth2Strategy exhibits unexpected behavior by returning a 400 error code instead of performing a redirect during

Currently, I am in the process of setting up Discord OAuth2 PKCE using Passport.js and the passport-oauth2 const discordStrategy = new OAuth2Strategy({ authorizationURL: 'https://discord.com/api/oauth2/authorize', tokenURL: 'https://disc ...

Problem with Safari: File downloaded with name "Unknown" due to Javascript issue

After successfully converting my data to text/csv, I can easily download the file in Chrome. However, when attempting to do so in Safari on an iPad or Mac, it opens a tab with the name "unknown" or "Untitled". The code snippet I am using for this is as fol ...

Limit the number of elements in an Angular object by using the filter function

I've implemented an angularjs filter method on a repeated array of items in an attempt to filter numbers using a limitTo filter. However, the result is not reflecting in the DOM. Below is the html code snippet: <div ng-controller="demo as d"> ...

Is it possible that only one number is printed when document.getElementById("demo").innerHTML = Math.ceil((Math.random()*10)-1); is executed?

How come the code document.getElementById(“demo”).innerHTML = Math.ceil((Math.random()*10)-1); is only displaying one number? function myFunction() { var bbb = document.getElementById("ilgis").value; for (i = 0; i <= bbb; i++) { //docum ...

Creating an HTML element within a three.js globe

I have a globe created using three.js Reference: I am trying to display an HTML div at a specific latitude/longitude on the globe. Can someone guide me on how to position the div at a particular lat/long? What I've attempted: I'm currently stu ...