Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

javascript - Nodejs web server calling requestListener twice when page is loaded

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

but this happens:

browser : Hello World 1
console : Counter 1
          Counter 2
[reload page]
browser : Hello World 3
console : Counter 3
          Counter 4

I run the code using the command line

$ node example.js

Here is the code:

  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 + '
');
    sys.puts('Counter ' + counter);
  }).listen(8000, "");
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...