0

Description:

Hello, following a simple and straight forward tutorial. Everything works fine, but I was just curious as to why I'm getting a double request received when I refresh/access my page?

Part of my code:

function onRequest(request, response){
    console.log('request received');
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write('Hello world baby');
    response.end();
}
//creating server
http.createServer(onRequest).listen(8888);
console.log("server has started");

Screenshot:

Image of double console log

Rahil Wazir
  • 10,007
  • 11
  • 42
  • 64
kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131
  • 4
    I bet it's because you're sending two requests. – Leonid Beschastny Mar 04 '15 at 16:03
  • @LeonidBeschastny I don't see how I could be sending two requests. – kemicofa ghost Mar 04 '15 at 16:04
  • 8
    Probably, your browser is trying to load `/favicon.ico` from your server. – Leonid Beschastny Mar 04 '15 at 16:04
  • 6
    Use your browser developer console to see actual HTTP requests. – Pointy Mar 04 '15 at 16:04
  • 1
    Debug each request with `console.log('request received:', request, response);` – gmo Mar 04 '15 at 16:06
  • 3
    @gmo it'll be a lot of useless data, something like `console.log('request received:', request.url);` will be much more useful. – Leonid Beschastny Mar 04 '15 at 16:07
  • @LeonidBeschastny you are right, it's trying to load the favicon.ico. I noticed after following your proposition: request.url. Thanks. Feel free to add the answer and I'll mark it as right. – kemicofa ghost Mar 04 '15 at 16:09
  • @Grimbode there is alresy a bunch of identical questions on stackoverflow. For example, here are two top links from google: [1](http://stackoverflow.com/questions/22219463/why-does-node-js-http-server-show-that-there-are-two-request-coming), [2](http://stackoverflow.com/questions/9650253/node-js-beginner-why-does-this-receive-2-responses). – Leonid Beschastny Mar 04 '15 at 16:14
  • @LeonidBeschastny, I searched directly on SO. The propositions proposed by SO when I wrote the title of the question didn't correspond. I'll look more in depth next time. – kemicofa ghost Mar 04 '15 at 16:15
  • Also make yourself familiar with your browser's debugging tools if you haven't already. – Felix Kling Mar 04 '15 at 16:26
  • @Grimbode I think it's not because I was using another search engine, but because I was searching for a different phrase - `node.js two requests`. – Leonid Beschastny Mar 04 '15 at 16:27
  • @LeonidBeschastny you're right.. `request.url` would be much more specific here. Good catch! – gmo Mar 04 '15 at 16:31

1 Answers1

2

Your browser is looking for the favicon.ico, then it sends a request for the actual content. Try to console.log both the request and response to get more information.

aludvigsen
  • 5,893
  • 3
  • 26
  • 37