nodejs - http.createServer seems to call twice

node.js

node.js Problem Overview


If I write the following program in node:

  http.createServer(function (req, res) {

    if( req.method == 'GET' ) {
      var body = ''; req.on('data', function(data) { body += data });
      req.on('end',  function() {
        console.log('request ended')
      });
    }

    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('142\n');
  }).listen(3500);

And then hit the server with http://xxx.xx.xxx.xx:35010 I see a request ended twice on my console -- I'm not sure why a single HTTP request is causing this to execute twice.

node.js Solutions


Solution 1 - node.js

That is normal - your browser makes more than one call.

Most browsers make a call to grab /favicon.ico for example.

Try to log the url:

console.log(req.url);

and you'll see what's being called.

Solution 2 - node.js

Generally, favicon.ico is fetched by the browsers. So, the two calls.

Solution to this issue can be checking for request URL if it's fetching favicon.ico or not.

http.createServer(function (req, res) {
    if (req.url != '/favicon.ico') {
        // do your stuffs
    }
}).listen(3500);

Solution 3 - node.js

Another thing to watch out for is that modern browsers may prefetch or preload pages. Chrome will sometimes even do this before you hit enter in the address bar!

It can be disabled under Privacy and security, but this will affect all browsing.

enter image description here

You can also check for header Purpose: prefetch and just return an error. (I'm not sure what the official response should be in production.)

This is unlikely to be happening frequently, but if you're testing an API it can be at best annoying and at worse dangerous for an unexpected request to suddenly be made.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWillView Question on Stackoverflow
Solution 1 - node.js3onView Answer on Stackoverflow
Solution 2 - node.jsMukesh ChapagainView Answer on Stackoverflow
Solution 3 - node.jsSimon_WeaverView Answer on Stackoverflow