I've the following 3 files. My error is "Can't set headers after they are sent". I've seen this but I cant figure out which function or callback is causing a write to the headers after they are sent. I've spent immense time on it. please help.
routes.js
"use strict";
var controller = require("./controller");
module.exports = function(app){
app.post('/master', function(req, res) {
controller.process(req, function(err, data) {
if( err ) {
return res.sendStatus(400);
} else {
res.sendStatus(200);
}
});// cb ends here
});// process ends here
}// route ends here
controller.js
module.exports.process = function(req, cb){
var jsonBody = req.body;
var type = jsonBody["strType"];
var id = jsonBody["id"];
var moment = require('moment');
if ( !type || !id ) {
return (cb(true, false));
}
if( type === "company" ) {
Company_strCode = jsonBody["Company_strCode"];
jsonBody.lastUpdate = moment().format();
delete jsonBody["strType"];
delete jsonBody["id"];
dbOps.companyUpsert(type, Company_strCode, jsonBody, cb);
dbOps.normalUpsert(type, id, jsonBody, cb);
return;
}
jsonBody.lastUpdate = moment().format();
delete jsonBody["strType"];
delete jsonBody["id"];
dbOps.normalUpsert( type, id, jsonBody, cb );
} //fnProcess ends
dbOps.js
"use strict";
var keyDef = require('../config/config.json')
var MongoClient = require('mongodb').MongoClient;
var host = keyDef.mongodb.host;
var port = keyDef.mongodb.port;
var db = keyDef.mongodb.db;
var username = keyDef.mongodb.username;
var password = keyDef.mongodb.password;
var url = "mongodb://"+host+":"+port+"/"+db;
module.exports.normalUpsert = function(type, id, jsonBody, cb){
MongoClient.connect(url, function(err, db){
if(err){
console.log("Mongodb connection error..");
return cb(true, false);
}
db.collection(type).update({"_id":id},{$set:(jsonBody)}, {upsert:true}, function(err){
if(err){
return cb(true, false);
}
cb(false, true);
});//func callback
});// mongoClient callback
};
module.exports.companyUpsert = function(type, Company_strCode, jsonBody, cb){
MongoClient.connect(url, function(err, db) {
if(err){
console.log("Mongodb connection error..");
return cb(true, false);
}
db.collection("Cinema").update({"Cinema_strCompanyCode":Company_strCode},{$set:{"tblCompany":jsonBody}}, {upsert:true}, function(err){
if(err){
return cb(true, false);
}
cb(false, true);
});//func callback
});// mongoClient callback
};