Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double request in Chrome with Nodejs

I'm doing a test with Nodejs to increment a global counter, according to the scripts below. Everything works, except that Chrome executes two sequential requests when I refresh it, which causes the counter to increment twice as well (see the image). In Postman and Firefox works fine and only one request occurs on refresh. I've done the tests running the app on Linux and Windows and the problem with Chrome holds. Anyone have any idea what might be happening?

server.js

const http = require('http');
const express = require('express');
const app = express();
const rotas = require("./route-test")(app);

const port = 3000;

const server = app.listen(process.env.PORT || port, function(){
    console.log('App listening port: ', port);
});

route-test.js

const myGlobalVars = require("./global-vars");

module.exports = (app) => {
    app.use('/', (req, res) => {
       res.end('Counter in: ' + myGlobalVars.counter); 
    });

    app.use(function(req, res, next){
        //console.log(req.originalUrl);
    });
}

global-vars.js

let myCounter = 0;

const _myVars = Object.create(Object.prototype, {
  dateInit: { 
    writable: false,
    configurable: false,
    value: new Date() 
  },
  counter: {
    configurable: false,
    get: function() { return myCounter++ },
    set: function(_val) {
      myCounter = _val;
    }
  }
});

module.exports = _myVars;

2 requests

like image 402
wBB Avatar asked Mar 03 '26 16:03

wBB


2 Answers

I check all 3 files... so in FireFox and Google Canary(developers version) we have only 1 request(we got 1 request and we increment only once myGlobalVars.counter ). in simple Google Chrome version we have 2 request. one of them is request for favicon.ico. so we just need to add condition to ignore favicon.ico request and dont increment twice our myGlobalVars.counter value...

in route-test.js

const myGlobalVars = require("./global-vars");

module.exports = (app) => {

  app.use('/', (req, res) => {

  // instead of this code res.end('Counter in: ' + myGlobalVars.counter);
  // add this condition
  if (req.url === '/') {
    res.end( `\n\n\nCounter in: ${myGlobalVars.counter}` );
  }

});


}
like image 116
maksymhlushek Avatar answered Mar 05 '26 06:03

maksymhlushek


I think it's the request that the browser makes to the server to get /favicon.ico resource.

like image 29
Breno Henrique Avatar answered Mar 05 '26 05:03

Breno Henrique