Node.js每个请求都有奇怪的多个代码执行

Max*_*Max 3 node.js

我之前做了一些节点实验

以下代码将"aaa"输出到控制台,并且浏览器会按预期等待响应.

var http = require("http");

http.createServer(function (req, res) {
  //res.writeHead(200);
  console.log("aaa");
  //res.end("hello");
  //console.log("test111");
  //res.end("bye");
}).listen(5555);
Run Code Online (Sandbox Code Playgroud)

输出:

aaa
Run Code Online (Sandbox Code Playgroud)

但是,只要我取消注释第一个res.end,节点就会在一次请求中将"aaa"写入控制台两次!

var http = require("http");

http.createServer(function (req, res) {
  res.writeHead(200);
  console.log("aaa");
  res.end("hello");
  //console.log("test111");
  //res.end("bye");
}).listen(5555);
Run Code Online (Sandbox Code Playgroud)

输出:

aaa
aaa
Run Code Online (Sandbox Code Playgroud)

最后,当我取消评论一切时,

var http = require("http");

http.createServer(function (req, res) {
  res.writeHead(200);
  console.log("aaa");
  res.end("hello");
  console.log("test111");
  res.end("bye");
}).listen(5555);
Run Code Online (Sandbox Code Playgroud)

输出:

aaa
test111
aaa
test111
Run Code Online (Sandbox Code Playgroud)

知道为什么每个请求都会执行两次console.log语句吗?

Dee*_*tan 8

在第一个示例中,浏览器没有得到回复并停在那里.

在第二个示例中,浏览器确实得到了回复,然后继续请求第二个请求的favicon.

尝试也记录请求网址:

var http = require("http");
http.createServer(function (req, res) {
  console.log("aaa", req.url);
  res.end("bye");
}).listen(5555);
Run Code Online (Sandbox Code Playgroud)

你会看到服务器正在运行:

aaa /
aaa /favicon.ico
Run Code Online (Sandbox Code Playgroud)


Ste*_*ire 5

这有你想要的答案:

NodeJS服务器为每个请求将变量递增2

它正在击中/和/favicon.ico.