首页 文章

Nodejs Http Server api执行流程请解释一下?

提问于
浏览
0

我有以下Nodejs程序

var http = require('http');
var url = require('url');
var server = http.createServer((req,res)=>{
  console.log("Enter into the 3000 port");
  res.end("hello world")
  console.log("Enter into the 3000 port");
}).listen(3000,()=>{console.log("the server is listen to the port 3000");});

我在浏览器中加载localhost:3000时运行这些代码,当我编写 console.log("Enter into the 3000 port"); 来检查执行内部如何工作时,我得到了以下输出 . OUTPUT:

the server is listen to the port 3000
Enter into the 3000 port
Enter into the 3000 port
Enter into the 3000 port
Enter into the 3000 port

但我已经在代码中编写了两次代码 console.log("Enter into the 3000 port"); ,但我不明白为什么它在单个请求上调用了两次,当我再次发送请求时它再次向我显示了一些输出可以解释 .

2 回答

  • 0

    这是正常的 - 您的浏览器会拨打多个电话 .

    例如,大多数浏览器都会调用抓取/favicon.ico .

    尝试记录网址:

    console.log(req.url);
    

    你会看到被叫的东西 .

  • 1
    var http = require('http');
    var url = require('url');
    var server = http.createServer((req,res)=>{
      if (req.url === '/favicon.ico') { return } // if you don't serve this hit 
      console.log(req.url);
      console.log("Enter into the 3000 port");
      res.end("hello world")
      console.log("Enter into the 3000 port");
    }).listen(3000,()=>{console.log("the server is listen to the port 3000");})
    

    大多数浏览器会自动查找* favicon.ico *,如果您愿意,可以自行查找

    code

相关问题