0

Query run successfully but Server closed And it give following error

Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)

As I find it send response on per loop that is the main reason. So my question how to send response after completing the loop?

    var addVenueAmenities = function(req, res) {
    var post={
    venue_id:req.params.venue_id,
    amenitie:req.body.amenitie
}


for(i=0;i<post.amenitie.length;i++){

data={
venue_id:post.venue_id,
amenitie:post.amenitie[i]
}

var query = "INSERT INTO  ?? SET  ?";
        var table = ["venue_amenities"];
        query = mysql.format(query,table);
        connection.query(query, data, function(err,rows){
            if(err) {

             res.json({"Error" : true, "Message" : "Error executing MySQL query"});
            } else {

             res.json({"Error" : false, "Message" : "Amenitie  added successfully"});

            }
        });
}
} 
 module.exports= addVenueAmenities;
Akhilendra
  • 1,137
  • 1
  • 16
  • 31
  • you must have a server running already on the same port – Nagaraju Apr 28 '17 at 10:08
  • Server running but after this error it stopped – Akhilendra Apr 28 '17 at 10:10
  • 1
    @Nagaraju That's not it. You're calling `res.json` in a loop, which sets JSON headers and writes data each time. You can't do that, after you've sent the headers you can only send a body. – Ben Fortune Apr 28 '17 at 10:16
  • 1
    Possible duplicate of [Error: Can't set headers after they are sent to the client](http://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client) – Ben Fortune Apr 28 '17 at 10:16
  • 1
    A response is only supposed to be sent ONCE. If you need to use a loop you can't sent multiple responses, iterate over the data first, create a json response and send it ONCE. Only ONE response should be sent. EVER! – Simon Hyll Apr 28 '17 at 10:47

1 Answers1

3

You are running in for loop and sending response again and again causing this problem.

for (i = 0; i < post.amenitie.length; i++) {
    if (err) {
        res.json({"Error": true, "Message": "Error executing MySQL query"});
    } else {
        res.json({"Error": false, "Message": "Amenitie  added successfully"});
    }
} 

You can use async library as below

async.map(post.amenitie,function (amenitie,callback) {
    var data= {
        venue_id:post.venue_id,
        amenitie:amenitie[i]
    }

    var query = "INSERT INTO  ?? SET  ?";
    var table = ["venue_amenities"];
    query = mysql.format(query,table);
    connection.query(query, data, function(err,rows){
        callback(err);
    });
},function (err,result) {
    if(err)
        res.json({"Error" : true, "Message" : "Error executing MySQL query"});
    else
        res.json({"Error" : false, "Message" : "Amenitie  added successfully"});
}); 
Jagdish Idhate
  • 7,513
  • 9
  • 35
  • 51