![](/img/trans.png)
[英]Loading two different types of data to a webpage with http.createServer's callback
[英]Why two times the callback invoked in CreateServer of http in nodejs
我正在尝试以下代码:
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);
当我从浏览器http:// localhost:8989连接时 ,
我收到了两次控制台打印的“接收的连接”。 为什么?
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);
将打印:
Received Connection...
URL: /
Received Connection...
URL: /favicon
这是因为浏览器会自动要求您提供图标,即您在标签中看到的小图标。 如果您从POSTMan,wget,curl或其他http工具触发请求,则只会看到一个请求。
可以通过使用console.log(req)
注销req
来跟踪。
查看原始请求,我们看到浏览器还为每个请求另外请求/ favicon。
url: '/',
url: '/favicon.ico',
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.