Hi All I'm a Newbie to Nodejs and Firbase as well.
I have a written a firebase function to save the data to Firebase DB VIA Firebase-Admin SDK.
But It always returns a error if I add a callback function
Error : Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
The Code is working fine if there is no callback function attached to the Firebase Function.
Working Code :
app.post('/add_project_status', function(req, res)
{
var status_id = Math.floor(new Date().getTime() / 1000);
var status_name = req.body.status_name.trim();
var status = req.body.status;
try
{
if (status != undefined)
{
status = 1;
}
else
{
status = 0;
}
if (status_id != '' && status_name != '')
{
var db = admin.database();
var ref = db.ref("status/" + status_id);
ref.set(
{
status_name: status_name,
status_id: status_id,
status: status
});
}
}
catch (error)
{
console.log("Data could not be saved." + error);
}
});
Error Code :
app.post('/add_project_status', function(req, res)
{
var status_id = Math.floor(new Date().getTime() / 1000);
var status_name = req.body.status_name.trim();
var status = req.body.status;
try
{
if (status != undefined)
{
status = 1;
}
else
{
status = 0;
}
if (status_id != '' && status_name != '')
{
var db = admin.database();
var ref = db.ref("status/" + status_id);
ref.set(
{
status_name: status_name,
status_id: status_id,
status: status
}, function(error)
{
if (error)
{
// console.log(" eoorr");
}
else
{
console.log(" suceess");
}
});
}
}
catch (error)
{
}
});
If I add this call back function code to firebase
var db = admin.database();
var ref = db.ref("status/" + status_id);
ref.set(
{
status_name: status_name,
status_id: status_id,
status: status
}, function(error)
{
if (error)
{
// console.log(" eoorr");
}
else
{
console.log(" suceess");
}
});
It gives me a Error
Error :
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:526:11) at ServerResponse.header (G:\xampp_new\htdocs\saiby\public\node_modules\express\lib\response.js:771:10) at ServerResponse.contentType (G:\xampp_new\htdocs\saiby\public\node_modules\express\lib\response.js:599:15) at ServerResponse.send (G:\xampp_new\htdocs\saiby\public\node_modules\express\lib\response.js:145:14) at done (G:\xampp_new\htdocs\saiby\public\node_modules\express\lib\response.js:1008:10) at tryHandleCache (G:\xampp_new\htdocs\saiby\public\node_modules\ejs\lib\ejs.js:261:5) at View.exports.renderFile [as engine] (G:\xampp_new\htdocs\saiby\public\node_modules\ejs\lib\ejs.js:461:10) at View.render (G:\xampp_new\htdocs\saiby\public\node_modules\express\lib\view.js:135:8) at tryRender (G:\xampp_new\htdocs\saiby\public\node_modules\express\lib\application.js:640:10) at Function.render (G:\xampp_new\htdocs\saiby\public\node_modules\express\lib\application.js:592:3)
can some one help me what has to be modified or removed from the piece of code to avoid this issue. TIA .