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,
I received two times the console print "Received Connection." Why?
答案 0 :(得分:3)
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工具发出请求,您只会看到一个请求。
答案 1 :(得分:2)
可以使用req
退出console.log(req)
来追踪这一点。
查看原始请求,我们看到浏览器还为每个请求请求/ favicon。
url: '/',
url: '/favicon.ico',