0

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.

hasin
  • 79
  • 6
  • Seems a duplicate of: https://stackoverflow.com/questions/22219463/why-does-node-js-http-server-show-that-there-are-two-request-coming – Volkorp Jan 31 '23 at 12:56
  • 1
    Does this answer your question? [Why does node.js, http-server, show that there are two request coming?](https://stackoverflow.com/questions/22219463/why-does-node-js-http-server-show-that-there-are-two-request-coming) – Dave Newton Jan 31 '23 at 13:02

1 Answers1

1

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.

  • You are right. It appears that on each page reload there were 2 requests being sent: one for the root page '/' and one for './favicon/ico' (the icon that goes next to the site name in the tab). I've now fixed this issue by adding an if statement so that if the URL is ./favicon.ico I exit the callback for that request. – hasin Jan 31 '23 at 13:01