RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

Why my node server processes the request twice?

I have following simple node server.

const http = require('http');

http.createServer(function(req, resp) {

    console.log("request arrived.")
    resp.writeHead(200, { 'Content-Type': 'application/json' });
    resp.end("Hello world!!");

}).listen(3000);

Whenever I hit the request using url http://localhost:3000/, it printing request arrived message two times.

I don't know,what is the exact reason for it. Will some please explain it.

I have attached screenshot. enter image description here

Upvotes: 1

Views: 1638

Answers (2)

Dan Kurth
Dan Kurth

Reputation: 91

In answer to the follow-up question "I have checked.But how we can avoid it?" answer is put the lines in previous answer just below the line that has http.createServer, so that you end up with something like following which contains 4 lines added to the original code in question:

const http = require('http');

http.createServer(function(req, resp) {
    if (req.url === '/favicon.ico') {
      res.end();
      return;
    }

    console.log("request arrived.")
    resp.writeHead(200, { 'Content-Type': 'application/json' });
    resp.end("Hello world!!");

}).listen(3000);

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239443

It is most likely that the browser is requesting for the favicon.ico file. You can confirm that by printing the URL, like this

console.log("request arrived for URL", req.url);

When I tried this on my machine, with Chrome browser, I got

request arrived for URL /
request arrived for URL /favicon.ico

If you want to avoid that, then you need to handle the favicon request specially. Probably, you can do something like this, as shown here

if (req.url === '/favicon.ico') {
    resp.writeHead(200, {'Content-Type': 'image/x-icon'} );
    resp.end();
    console.log('favicon requested');
    return;
}

console.log("request arrived.")
resp.writeHead(200, { 'Content-Type': 'application/json' });
resp.end("Hello world!!");

Upvotes: 5

Related Questions