Node.js双重console.log输出

我正在学习Node.js,我想了解代码吐出重复console.log输出时的“为什么”,但只有一个response.write输出。

下面我简单的代码示例:

var http = require('http'); http.createServer(function(request, response){ response.writeHead(200, {'Content-type': 'text/plain'}); console.log('hello 1'); response.write('Hello world'); console.log('hello 2'); response.end(); }).listen(8000); 

并在我的控制台/terminal上,我得到:

你好1

你好2

你好1

你好2

谢谢。

一些浏览器也发送请求来定位favicon.ico文件。 由于该文件默认不存在,因此浏览器(特别是Chrome )将始终发送两个请求:一个用于原始请求的文件,另一个用于favicon.ico。 这是Chrome中的一个已知错误 ,已经在版本29中进行了修复。然而, Firefox仅在第一个请求中才会请求favicon.ico。 如果您使用console.log请求URI path ,则必须看到对localhost:8000/favicon.ico.的请求localhost:8000/favicon.ico.

 var http = require('http'); http.createServer(function(request, response){ response.writeHead(200, {'Content-type': 'text/plain'}); if(request.url === '/favicon.ico') { console.log('Favicon was requested'); } console.log('hello 1'); response.write('Hello world'); console.log('hello 2'); response.end(); }).listen(8000); 

我自己也有同样的问题,我发现使用类似的东西

 var http = require('http'); http.createServer(function(req,res) { if(req.url === '/favicon.ico') { //everything here is ignored } res.writeHead(200,{"Content-Type": "text/plain"}); res.write("Hello World\n"); res.end(); console.log("Connection made"); }).listen(1337, "127.0.0.1"); console.log("Server running at http://127.0.0.1:1337/"); 

足以避免这种行为。 出于某种原因,当我检查req.url并将其与'/favicon.ico'进行比较时,没有任何内容被发送到控制台,事实上,该块中的所有内容都将被忽略。 我不知道这种行为是否可以预料,但你一定可以尝试。

如果你输出标题,你告诉服务器你find了favicon,因此响应被处理,不pipe你得到什么双console.log() 。 相反,在发送writeHead()或发送404之前结束它。

 var http = require('http'); http.createServer(function (req, res) { if(req.url === '/favicon.ico') { res.writeHead(404); res.end(); } else { res.writeHead(200, {'Content-Type': 'text/plain'}); } //code here... res.end(); } 

简而言之,前面提到的重复是favicon请求的结果,为了避免这个问题,我build议你这个简单的snipet:

 var pathname = url.parse(request.url).pathname; if(pathname != '/favicon.ico') console.log('hello 1'); 

它也可以是像JSONView的Chrome插件。 我只是想弄明白,直到我尝试隐身,意识到它不再造成问题。 也正在请求一个JSON文件。