title: node js server headers
body: <p>I am currently a beginner at web-development. Therefore naturally i am using node.js as a back-end for an app that i am creating that involves getting data using REST and then searching and sorting. The part that i am stuck on is how do headers work node.js and in general on web server. The code i have below is basically setting up a server on port 3000 , and then i have a counter that counts how many times the endpoint was hit. What i dont get is the error that node throws. Therefore i tried to rewrite the headers. From the research i have done online is that once the server which is node.js in this case makes a handshake with the client, which is our front end, it sets a header. Then the client can make a request to server using api routes and get a response. What i dont understand is how headers are used in this ?</p>
  
  <pre><code>const express = require('express');
  const app = express();
  const port = 3000;
  
  var counter=0;
  
  app.get('/',(req,res) =&gt; {
      res.send("Hello World");
      console.log("First Request");
      counter++;
  
      if(counter%2)
      {
             res.setHeader("Content-Type", "text/html");
             res.send("Second Request");
      }
  
  
  })
  
  
  app.listen(port,()=&gt;{
      console.log("App is listening on port 3000");
  })
  </code></pre>
  
  <p>The exception it throws is this</p>
  
  <pre><code>rror [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
      at ServerResponse.setHeader (_http_outgoing.js:470:11)
      at app.get (/Users/taherhuzefa/Desktop/Personal/groupme_extension/index.js:14:16)
      at Layer.handle [as handle_request] (/Users/taherhuzefa/Desktop/Personal/groupme_extension/node_modules/express/lib/r
  outer/layer.js:95:5)
      at next (/Users/taherhuzefa/Desktop/Personal/groupme_extension/node_modules/express/lib/router/route.js:137:13)
      at Route.dispatch (/Users/taherhuzefa/Desktop/Personal/groupme_extension/node_modules/express/lib/router/route.js:112
  :3)
      at Layer.handle [as handle_request] (/Users/taherhuzefa/Desktop/Personal/groupme_extension/node_modules/express/lib/r
  outer/layer.js:95:5)
      at /Users/taherhuzefa/Desktop/Personal/groupme_extension/node_modules/express/lib/router/index.js:281:22
      at Function.process_params (/Users/taherhuzefa/Desktop/Personal/groupme_extension/node_modules/express/lib/router/ind
  ex.js:335:12)
      at next (/Users/taherhuzefa/Desktop/Personal/groupme_extension/node_modules/express/lib/router/index.js:275:10)
      at expressInit (/Users/taherhuzefa/Desktop/Personal/groupme_extension/node_modules/express/lib/middleware/init.js:40:
  5)
  </code></pre>