node.jshttpserverreq

NodeJS http request event listener firing more than once


I'm new to backend development so have just made my first server using NodeJS and the http module. This is my code so far:

const http = require("http");
let count = 0;
const server = http.createServer((req, res) => {
  res.write(count.toString());
  //tells the server that all of the headers and body have been sent, so the message is complete
  res.end();
  count += 1;
});

server.listen(3000);

I understand how almost all of this code works. However, whenever I refresh the page on my local environment (send a new request) I would expect the displayed response to increment by 1, however, it increments by 2. The only reason I can think this would happen is that the request event listener is being fired twice on each page reload, however, I cannot find anything to help me with this issue so any help would greatly be appreciated.


Solution

  • If i understand what this website says https://www.w3schools.com/nodejs/met_http_createserver.asp

    The requestListener is called every time a request is sent to the server.

    You can check in your Navigator console (in the Network sub-tab) the different requests sent to your server.

    Network Sub Tab

    Maybe there are multiple requests sent to your server on page reload. I hope this helped, otherwise, you can try to log in your requestListener the req object to know what triggers it, and where does it come from.