0

I am new to node.js and learning from tutorials online. I was trying out the following piece of code :

var http = require("http");

// create a server
http.createServer(function(req, res) {
    console.log("Received Request");
    res.writeHead(200, {'Content-Type':'application/json'});
    res.end("{'status':'200', 'message':'Hello World'}");
    console.log("Response Sent");
}).listen(process.env.PORT, process.env.IP);

I did receive the correct response but in console the output was :

Received Request
Response Sent
Received Request
Response Sent

I wanted to know why was my code running twice ?? Am I making some mistake ? Please help !!

3 Answers3

3

the best way to debug is to check the url

var http = require("http");

// create a server
http.createServer(function(req, res) {
    console.log(req.url);//add this line, I hope it will help
    console.log("Received Request");
    res.writeHead(200, {'Content-Type':'application/json'});
    res.end("{'status':'200', 'message':'Hello World'}");
    console.log("Response Sent");
}).listen(process.env.PORT, process.env.IP);

Also as Bassam Rubaye pointed out it might most likely due to favicon in your case

techblu3
  • 170
  • 9
2

When you access a url using the browser , the browser will send a request for the favicon, then send another request for the content, that's why you are seeing two requests !

Use PostMan and request the same url , you should see only one request.

Bassam Rubaye
  • 302
  • 1
  • 4
2

No mistake--this is normal! Your browser makes multiple requests. There's a similar answer at nodejs - http.createServer seems to call twice.

Hope you're having fun learning node.js!

Community
  • 1
  • 1
hxlnt
  • 618
  • 7
  • 7