Variable is incremented twice in node.js http callback function

时间秒杀一切 提交于 2019-12-07 06:56:38

问题


I was playing around with node.js and something strange happens when you run this code:

var http = require("http");
var i = 0;

function onRequest(request, response) {  
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("You're number " + i++);
  response.end();
}

http.createServer(onRequest).listen(8888);

I would expect it to behave like a page views counter, but with each refresh of the browser tab i get the result of what seems to be i=i+2 instead of a simple increment. Could someone explain this behavior to me?


回答1:


Your browser is hitting your server for favicon.ico as well. Each request increments i, and the request for favicon.ico counts.

Use a tool such as Fiddler or WireShark to see this behavior yourself.




回答2:


I bet it's the favicon request that browsers love to send over and over again.



来源:https://stackoverflow.com/questions/10131112/variable-is-incremented-twice-in-node-js-http-callback-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!