在节点http服务器中计算访问者

use*_*176 6 http count node.js

我的源代码:

 var http = require("http");
 var count=1;

 http.createServer(function(request, response) {
 response.writeHead(200, {"Content-Type": "text/plain"});    
 response.write("Hi, you are number "+count+" visitors");
 response.end();
 count++;
  }).listen(8888);  
Run Code Online (Sandbox Code Playgroud)

我每次访问都得到1,3,5,7,..... 为什么要将计数增加2?

ale*_*lex 10

请求favicon.ico是触发额外请求(我通过记录每个请求的详细信息然后通过Chrome发出正常请求来确认这一点).

您需要明确查看您想要匹配的请求类型(网址,方法等).

另外,请记住,如果您的服务器死了,它可能会在某个阶段,您的计数将被重置.如果你不想这样,你应该把它保存在不太易变的地方,比如数据库.