Nodejs Web服务器在页面加载时两次调用requestListener [英] Nodejs web server calling requestListener twice when page is loaded
问题描述
以下是文档中的示例Web服务器,带有添加的计数器.每当客户端/浏览器请求页面时,它将计数器打印到控制台.
The following is the example web server from the documentation, with an added counter. It prints the counter to the console whenever a client/browser requests the page.
但是,浏览器要求两次调用它.为什么?
However, it's being called twice when requested by the browser. Why?
这是我期望发生的事情:
This is what I would expect would happen:
browser : Hello World 1
console : Counter 1
[reload page]
browser : Hello World 2
console : Counter 2
但这会发生:
browser : Hello World 1
console : Counter 1
Counter 2
[reload page]
browser : Hello World 3
console : Counter 3
Counter 4
我使用命令行运行代码
$ node example.js
这是代码:
var
http = require('http'),
counter = 0,
sys = require('util');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
counter++;
res.end('Hello World ' + counter + '\n');
sys.puts('Counter ' + counter);
}).listen(8000, "");
推荐答案
在编程中,遇到困难时,跟踪代码以更好地了解正在发生的情况总是很方便的.最简单的方法是放入更多的debug/print语句,直到您看到正在发生的事情为止.
In programming, when stuck, it's always handy to trace the code to better understand what's happening. The easiest way to do this is to put more debug/print statements in till you can see what's going on.
将sys.puts行更改为:
Change the sys.puts line to:
sys.puts('Counter ' + counter + " from " + req.url);
我想您会发现第二个请求是浏览器请求该网站的网站图标.
I think you'll find that the 2nd request is the browser requesting the favicon for the site.
这篇关于Nodejs Web服务器在页面加载时两次调用requestListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!