xRobot
xRobot

Reputation: 26567

Nodejs and simple math operations that doesn't work

I just need a way to decrement the coins of the user every time the page is refreshed. This is my program:

    var http = require('http');

    var coins = 100;

    var server = http.createServer(function (req, res) {
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.write("Hello World");

      coins -= 1;
      res.write('Your coins: ' + coins + '\n');

      res.end();
    })

    server.listen(1338, '127.0.0.1');

    console.log('Server running at http://127.0.0.1:1338/');

This is what I get every time I refresh the page:

Your coins: 99
Your coins: 97
Your coins: 95
Your coins: 93
Your coins: 91
Your coins: 89
Your coins: 87
...

As you can see, it decrements by 2 instead of 1. Why?

Upvotes: 3

Views: 278

Answers (2)

weirdpanda
weirdpanda

Reputation: 2626

Let's look at it a little more deeply from a browser's point of view. The browser loaded your favicon.ico which is a tiny (usually 24x24) icon next to your tab's title.

And that request was handled by the code (correctly pointed out in the answer).

The solution seems simple: 1) use XHR with pre-flight disabled (for testing); or ignore the OPTIONS verb; 2) ignore the /favicon.ico URL.


In case this is because of OPTIONS which is the pre-flight verb, you can have a explicit GET handler.

You can look at this sub-section of the official Http module documentation. :)


So, after some digging around, OPTIONS was the culprit (for XHR). The following piece should work:

var http = require('http');

var coins = 100;

var server = http.createServer();
server.on( 'request', function( req, res ) {

    console.log( req.method );
    var method = req.method;
    if ( method === 'GET' && req.url.indexOf( 'favicon.ico' ) === -1 ) {
        coins -= 1;
    }


    res.writeHead(200, {
        'Content-Type': 'text/plain',
        'Access-Control-Allow-Origin': '*'
    });
    res.write("Hello World");
    res.write('Your coins: ' + coins + '\n');

    res.end();

} );

server.listen(1338, '127.0.0.1');

console.log('Server running at http://127.0.0.1:1338/');

Upvotes: 6

Artem Arkhipov
Artem Arkhipov

Reputation: 7455

Finally found that! When you refresh the page in a browser it makes two GET requests: One for /favicon.ico and another for /.

Both of the requests are handled by this code. To avoid this you may write code to ignore favicon request.

var http = require('http');

var coins = 100;

var server = http.createServer(function (req, res) {
  if (req.url === '/favicon.ico') { // here is the solution
      return res.end();
  }  
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write("Hello World");

  coins -= 1;
  res.write('Your coins: ' + coins + '\n');

  res.end();
})

server.listen(1338, '127.0.0.1');

console.log('Server running at http://127.0.0.1:1338/');

Upvotes: 1

Related Questions