我是 Node.js 的新手。我刚刚编写了一个 http 服务器模块,其中包含一个计数变量,用于存储模块接收到 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 应该显示 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
) 发出请求时,它会增加计数。(我每次都收到双重请求,当我在某处阅读时,这是由于浏览器发送另一个请求来获取 favicon.ico,好吧,好吧,这不是我的问题)。我的问题是,当我向 test.js ( ) 发送请求时http://localhost:8889
,我总是会收到我已经向 server.js 发出的请求数量加上一个额外的请求!换句话说,如果http://localhost:8888
显示我 1,http://localhost:8889
它从我的服务器模块读取相同的值显示 2!
任何人都知道为什么会这样?提前致谢!