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

时间:2013-08-20 03:06:32

标签: node.js http count

我的源代码:

 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);  

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

3 个答案:

答案 0 :(得分:10)

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

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

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

答案 1 :(得分:0)

如果您的服务器只是一个简单的计数器并且知道favicon.ico的请求正在触发额外的请求,那么您可以将每个请求简单地计为一半,这样就会产生确切的访问次数。

counter = counter + 0.5;

答案 2 :(得分:0)

您可以忽略favicon.ico的请求:

var server = http.createServer(function (req, res) {
    if(req.url === '/favicon.ico'){
        console.log('favicon');
        return;
    }
    userCount++;
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.write('Hello!\n');
    res.write('We have had ' + userCount + ' visits!\n');
    res.end();

});