Ricardo Martin
Ricardo Martin

Reputation: 129

Cannot set headers after they are sent to the client in Node.JS

I am quite new to Node.JS and i am trying to create a GET endpoint to retrive some information from MongoDB. I have set my route and my controller to handle the GET request. When i am testing this controller with Postman i am getting an error on the Node console, "Cannot set headers after they are sent to client", but i can see the correct result on the Postman response. My code is as follow:

'use strict'
const Area = require('../models/area');

exports.get_areas = (req, res, next)=> {
Area.find( {})
    .then(data=>{
        let flat = data.reduce((data, {price, streets}) => {
            streets.forEach(({name, locations}) => {
                locations.forEach(({type,code}) => {
                    data.push({price,name,type,code})
                })
            })
            res.json(data);

        }, [])
        console.log(flat);


    })
    .catch(error=>{
        return next(error);
    });

}

If i just have the controller without the reducer. I do not have this problem:

exports.get_areas = (req, res, next)=> {
Area.find( {})
    .then(data=>{
            res.json(data);
        })
    .catch(error=>{
        return next(error);
    });
}

In this case my JSON object has the following structure:

[{
    "price": 20,
    "streets":[{
           "name": "nameA",
           "locations":[{
               "type": "normal",
               "code": "code1"
            }]
        }]
 }]

Where is my mistake? i want to return a Flat JSON and not a nested JSOn, and for this reason i am trying to use the reduce().

Upvotes: 1

Views: 453

Answers (1)

moodseller
moodseller

Reputation: 212

It is because you are returning your data as res.json(data); inside of a loop. Move it out of the reduce function code block as you are trying to send multiple response amounts to a single request.

let flat = data.reduce((data, {price, streets}) => {
    streets.forEach(({name, locations}) => {
        locations.forEach(({type,code}) => {
            data.push({price,name,type,code})
        })
    })

}, [])
res.json(flat);

Upvotes: 1

Related Questions