查询运行成功,但服务器已关闭并且出现以下错误
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
我发现它在每个循环上发送响应是主要原因。所以我的问题是如何在完成循环后发送响应?
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;
答案 0 :(得分:3)
您正在for loop
中运行并一次又一次地发送响应导致此问题。
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"});
}
}
您可以使用async库,如下所示
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"});
});