Node.js双console.log输出 [英] Node.js double console.log output

查看:79
本文介绍了Node.js双console.log输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm learning Node.js and I'd like to understand the "why" when code spits out duplicated console.log outputs but only a single response.write outputs.

这里是我的简单代码示例:

Heres my simple code example:

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);

在我的控制台/终端上,我得到:

And on my console/terminal I get:


hello 1

hello 1

hello 2

hello 1

hello 2

谢谢。

推荐答案

某些浏览器还会发送请求以找到 favicon.ico 文件。由于默认情况下该文件不存在,因此浏览器(特别是 Chrome )将始终发送两个请求:一个请求原始请求的文件,另一个请求favicon.ico。这是Chrome中的已知错误,并且已在版本29中修复。但是,Firefox 仅在第一个请求中请求favicon.ico。如果您 console.log 请求URI 路径,则必须看到对 localhost:8000 / favicon.ico的请求。

Some browsers also send a request to locate the favicon.ico file. Since the file isn't present by default, a browser(Chrome in particular) will always send two requests: one for the originally requested file and another for favicon.ico. This is a known bug in Chrome and has been fixed in version 29. Firefox, however, requests for favicon.ico only for the first request. If you console.log the request URI path, you must see a request to 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);

这篇关于Node.js双console.log输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆