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 と呼びましょう。これは、サーバー モジュールを起動しますが、同時に別のポート (8889 としましょう) で http 要求をリッスンします。これまで務めてきました。
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 に対して既に行ったリクエストの数に加えて、1 つの余分なリクエストが常に取得されることです。つまり、サーバー モジュールから同じ値を読み取るとhttp://localhost:8888
1 が表示され、2 が表示されます。http://localhost:8889
なぜそうなのか、誰にも手がかりがありますか?前もって感謝します!