简体   繁体   English

为什么两次在Node.js中的http的CreateServer中调用两次回调

[英]Why two times the callback invoked in CreateServer of http in nodejs

i am trying with following code: 我正在尝试以下代码:

const  http = require('http');
const fs = require('fs');


var hServer = http.createServer( (req, res) => {
        console.log ("Received Connection..");
        fs.readFile('./index.html', function(err, page) {
                res.writeHeader(200, {"Content-Type": "text/html"});
                res.write(page);
                res.end();

        });
});

hServer.listen(8989);

When i connect from browser http://localhost:8989 , 当我从浏览器http:// localhost:8989连接时
I received two times the console print "Received Connection." 我收到了两次控制台打印的“接收的连接”。 Why? 为什么?

const  http = require('http');
const fs = require('fs');


var hServer = http.createServer( (req, res) => {
        console.log ("Received Connection...");
        console.log('URL: ' + req.url);
        fs.readFile('./index.html', function(err, page) {
                res.writeHeader(200, {"Content-Type": "text/html"});
                res.write(page);
                res.end();

        });
});

hServer.listen(8989);

Will print: 将打印:

Received Connection...
URL: /
Received Connection...
URL: /favicon

It is because the browser automatically ask for the favicon, the little icon you see in your tabs. 这是因为浏览器会自动要求您提供图标,即您在标签中看到的小图标。 If you fire your request from POSTMan, wget, curl, or other http tools, you'll only see one request. 如果您从POSTMan,wget,curl或其他http工具触发请求,则只会看到一个请求。

This can be traced down by logging out req using console.log(req) . 可以通过使用console.log(req)注销req来跟踪。

Looking at the raw request we see that the browser additionally requests /favicon for each request. 查看原始请求,我们看到浏览器还为每个请求另外请求/ favicon。

url: '/',
url: '/favicon.ico',

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM