ERR_HTTP_HEADERS_SENT caused by response to POST request after refresh node.js Express. res.send inside fs.watch callback

Viewed 9

On my webpage user can enter text and press send. this causes the server to append the message to a json object stored in a file. when this file is altered it then sends the new json to the client.

app.post("/recieve",function(req,res){
  watcher = fs.watch(__dirname+"/msgs/msg.json", (eventName, filename) => {
    watcher.close();
    fs.readFile(__dirname+"/msgs/msg.json", (err,data) => {
      return res.send(data);
    });
  });
})

here is the client side

async function recieveMSG(){
  $.ajax({
    url: "recieve",
    type: "POST",
    contentType: "text; charset=utf-8"
  }).done(function(data){
    $("#msgbox").html("<br>"+data+"<br>");
    recieveMSG();
  });
}

recieveMSG();

As shown in the code above, the client sends a POST request to the server. Next after the json file is changed the server responds to the POST request with the json. I know this may be the completely wrong way to do it, but I want to know why res.send(data) is being called twice on the same res object.

It seems after the first refresh the recieve POST request just doesnot do anything

1 Answers
app.post("/recieve",async function(req,res){
  try{
  watcher.close();
  }
  catch(e){
    console.log("WatcherUndefined --first execution");
  }
  watcher = fs.watch(__dirname+"/msgs/msg.json", (eventName, filename) => {
  watcher.close();
    fs.readFile(__dirname+"/msgs/msg.json", (err,data) => {
      return res.send(data);
    });
  });
})

The problem was that the watcher wasn't getting closed after the client refreshed/disconnected. After the client refreshed the res object generated by their stale request is unusable. I believe that the watcher's callback was never redefined with the new res object (after refresh). I do not know if my assumption is correct, and would like to hear other's thoughts on this as I am new to nodejs.

Related