NodeJS服务器执行两次?

Mar*_*rin 1 node.js

我尝试使用以下代码开发基本的HTTP服务器:

var http = require("http");

http.createServer(function(request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
}).listen(8888);
Run Code Online (Sandbox Code Playgroud)

并且工作正常并且页面返回:Hello World

之后我尝试了解NodeJS服务器中的无限循环并发现:使用此代码时:

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

http.createServer(function(request, response) {
    n++;
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    console.log('call: %d', n);
    response.end();
}).listen(8888);
Run Code Online (Sandbox Code Playgroud)

并且工作精细页面返回:Hello World

但看到日志我发现一个奇怪的结果,当页面刷新.呼叫:2呼叫:3基本上每次呼叫(页面刷新)服务器执行两次,为什么?这是每次调用时运行的线程数?

Lee*_*dka 5

试试这样:

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

http.createServer(function(request, response) {
    if(request.url != '/favicon.ico')
    {
       n++;
       response.writeHead(200, {"Content-Type": "text/plain"});
       response.write("Hello World");
       console.log('call: %d', n);
       response.end();
    }
}).listen(8888);
Run Code Online (Sandbox Code Playgroud)