Node.js:从另一个模块读取variables返回错误的值

我是Node.js的新手 我刚刚写了一个http服务器模块,其中有一个countvariables,用于存储模块接收到http请求的次数:

var http = require("http"); var count = 0; //no of requests so far function start() { function onRequest(request, response) { console.log(count + ": Request received in Main Server"); count++; response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello! you are request no. " + count); response.end(); } http.createServer(onRequest).listen(8888); console.log("Main Server has started."); } function getCount() { return count; } exports.getCount = getCount; exports.start = start; 

然后我写了另一个服务器,我们称它为test.js,启动服务器模块,但同时监听另一个端口上的http请求,比如说8889. test.js应该显示多less个请求server.js已经服务到目前为止。

 var http = require("http"); var server = require("./server"); server.start(); function onRequest(request, response) { console.log("Request received in Test Server"); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello! Server app has served: " + server.getCount()); response.end(); } http.createServer(onRequest).listen(8889); console.log("Test Server has started."); 

当我运行test.js,并向server.js( http://localhost:8888 )发出请求时,它加起来就是count。 (我每次都得到了两次请求,这是因为浏览器发送了另一个请求来获取favicon.ico,好,很好,这不是我的问题)。 我的问题是,当我发送请求到test.js( http://localhost:8889 )时,我总是得到我已经对server.js进行的请求数量加上一个额外的! 换句话说,如果http://localhost:8888显示我1, http://localhost:8889从我的服务器模块读取相同的值显示2!

任何人都有一个线索,为什么是这样的? 提前致谢!

当你从浏览器中进行刷新时,请求通常是(我总是相信,在Chrome中,我知道它总是,不像其他浏览器那样肯定)按照这个顺序:

 yourdomain.com/ 

其次是

 yourdomain.com/favicon.ico 

所以,你在第一个请求之后显示计数。 然后你的图标被请求,这是递增你的计数的价值。 如果你从浏览器发出请求,你永远不会在两个窗口中看到相同的值,因为在你能够请求你的8889端口之前,你的favicon请求总是会进来的。 我想,这在理论上是可能的。 如果你可以在X毫秒的时间内在两个窗口中刷新,你可以在favicon请求之前ping 8889,但是如果你在本地机器上工作,这个毫秒数将会很小,因此是不可能的。

如果你想validation这个,你可以做一个这样的简单的检查:

 if(request.url.match(/favicon.ico/i) === false) count++; 

哪些应该保持您的计数更新为favicon请求。