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;

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}` );
}
});
}
I think it's the request that the browser makes to the server to get /favicon.ico resource.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With