title: NodeJS Express MySQL post request throwing "Cannot set headers after they are sent to the client"
body: <p>I try to send some MySQL results back via a express post request, but no matter what I try, there's always the following error:</p>
  
  <pre><code>(node:3743) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
      at validateHeader (_http_outgoing.js:503:11)
      at ServerResponse.setHeader (_http_outgoing.js:510:3)
      at ServerResponse.header (/home/dvs23/projects/Group/Visualizer/node_modules/express/lib/response.js:767:10)
      at ServerResponse.send (/home/dvs23/projects/Group/Visualizer/node_modules/express/lib/response.js:170:12)
      at ServerResponse.json (/home/dvs23/projects/Group/Visualizer/node_modules/express/lib/response.js:267:15)
      at ServerResponse.send (/home/dvs23/projects/Group/Visualizer/node_modules/express/lib/response.js:158:21)
      at /home/dvs23/projects/Group/Visualizer/index.js:193:11
      at &lt;anonymous&gt;
      at process._tickCallback (internal/process/next_tick.js:160:7)
  (node:3743) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
  (node:3743) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
  </code></pre>
  
  <p>The important part of the code is: </p>
  
  <pre><code>app.post('/getNews', (req, res) =&gt; {
    var prom = new Promise(function(resolve, reject) {
        //create nodes for result
        con.connect(function() {
          console.log("Connected!");
          con.query("SELECT ID,length(Text) FROM news;", function(err, result, fields) {
            if (err) {
              console.log(err);
              reject(err);
              return;
            }
  
            var nodesArr = [];
            result.forEach((row) =&gt; {
              nodesArr.push({
                "id": row["ID"],
                "size": row["length(Text)"]
              });
            });
  
            con.query("SELECT * FROM newsSim;", function(err, result2, fields) {
              if (err){
                console.log(err);
                reject(err);
                return;
              }
  
              var linksArr = [];
              result2.forEach((row) =&gt; {
                linksArr.push({
                  "source": row["TID1"],
                  "target": row["TID2"],
                  "value": row["SIM"]
                });
              });
              console.log({
                "nodes": nodesArr,
                "links": linksArr
              });
              resolve({
                "nodes": nodesArr,
                "links": linksArr
              });
            });
          });
        });
      })
      .then(function(result) {
        console.log(result);
        res.send(result); //send result to client
      }, function(err) {
        console.log("END"+err);
        res.send({
          "nodes": [],
          "links": []
        });
      });
  });
  </code></pre>
  
  <p>App is my express-app, the request comes from a static HTML page, which is also served by the NodeJS server, via jQuery.<br>
  I already use a promise, so how is it possible send is already called??
  Also without promises, just nested queries, there's the same error (obviously without the UnhandledPromiseRejectionWarning stuff).  </p>
  
  <p>EDIT:  </p>
  
  <p>It's not a problem with the nested MySQL-queries, even the following does not work:  </p>
  
  <pre><code>app.post('/getNews', (req, res) =&gt; {
    //var text = req.fields["text"];
  
    var prom = new Promise(function(resolve, reject) {
        //create nodes for result
        con.connect(function() {
          console.log("Connected!");
          con.query("SELECT ID,length(Text) FROM news;", function(err, result, fields) {
            if (err) {
              console.log(err);
              reject(err);
              return;
            }
  
            var nodesArr = [];
            result.forEach((row) =&gt; {
              nodesArr.push({
                "id": row["ID"],
                "size": row["length(Text)"]
              });
            });
  
            resolve(nodesArr);
            return;
          });
        });
      })
      .then(function(news) {
        console.log(news);
        //if (res.headersSent) return;
        res.send(news); //send result to client
      }, function(err) {
        console.log("END"+err);
        //if (res.headersSent) return;
        res.send({
          "nodes": [],
          "links": []
        });
      });
  });
  </code></pre>
  
  <p>If I use the if(res.headersSent), simply nothing is sent back to my site, neither an empty result, nor the real result, which is fetched as wanted -> I can log it to console...</p>
  
  <p>EDIT2:</p>
  
  <pre><code>app.post('/getNews', (req, res) =&gt; {
    //var text = req.fields["text"];
    req.connection.setTimeout(6000000, function () { 
      console.log("Timeout 2");
      res.status(500).end(); 
    });
  
    var prom = new Promise(function(resolve, reject) {
        //create nodes for result
        con.connect(function() {
          console.log("Connected!");
          con.query("SELECT ID,length(Text) FROM news;", function(err, result, fields) {
            if (err) {
              console.log(err);
              reject(err);
              return;
            }
  
            var nodesArr = [];
            result.forEach((row) =&gt; {
              nodesArr.push({
                "id": row["ID"],
                "size": row["length(Text)"]
              });
            });
  
            con.query("SELECT * FROM newsSim;", function(err2, result2, fields2) {
              if (err2){
                console.log(err2);
                reject(err2);
                return;
              }
  
              var linksArr = [];
              result2.forEach((row) =&gt; {
                linksArr.push({
                  "source": row["TID1"],
                  "target": row["TID2"],
                  "value": row["SIM"]
                });
              });
              resolve({
                "nodes": nodesArr,
                "links": linksArr
              });
              return;
            });
          });
        });
      })
      .then(function(news) {
        //if (res.headersSent) return;
        res.send(news); //send result to client
        console.log(news);
      }, function(err) {
        console.log("END"+err);
        //if (res.headersSent) return;
        res.send({
          "nodes": [],
          "links": []
        });
      });
  });
  </code></pre>
  
  <p>Tried to set timeout, but Now the error occurs <strong>before</strong> the timeout callback is called...</p>
  
  <pre><code>(node:9926) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
      at validateHeader (_http_outgoing.js:503:11)
      at ServerResponse.setHeader (_http_outgoing.js:510:3)
      at ServerResponse.header (/home/dvs23/projects/Group/Visualizer/node_modules/express/lib/response.js:767:10)
      at ServerResponse.send (/home/dvs23/projects/Group/Visualizer/node_modules/express/lib/response.js:170:12)
      at ServerResponse.json (/home/dvs23/projects/Group/Visualizer/node_modules/express/lib/response.js:267:15)
      at ServerResponse.send (/home/dvs23/projects/Group/Visualizer/node_modules/express/lib/response.js:158:21)
      at /home/dvs23/projects/Group/Visualizer/index.js:198:11
      at &lt;anonymous&gt;
      at process._tickCallback (internal/process/next_tick.js:160:7)
  (node:9926) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
  (node:9926) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
  Timeout 2
  </code></pre>