【问题标题】:Nodejs Http Server api Execution flow please Explain?Nodejs Http Server api 执行流程请解释一下?
【发布时间】:2019-05-11 00:40:03
【问题描述】:

我有以下 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"); 以检查内部执行方式时,我得到以下输出。 输出:

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"); 在代码中两次,但我不明白为什么它在单个请求中调用了两次,当我再次发送请求时,它再次向我显示了一些输出,任何人都可以解释。

【问题讨论】:

  • 因为您告诉它在每个请求上记录两次相同的消息。使用return res.end(message); 和/或删除额外的日志。
  • @Luis Estevez 您能否在此详细解释一下,谢谢。 :)
  • 是因为你的浏览器被调用了2次。当你通过 CURL 之类的东西请求时,它应该打印一次。

标签: javascript node.js http nodes node-modules


【解决方案1】:

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

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

尝试记录网址:

console.log(req.url);

你会看到被调用的内容。

【讨论】:

    【解决方案2】:
    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-15
      • 1970-01-01
      • 2016-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多