我有以下简单的节点服务器。
const http = require('http');
http.createServer(function(req, resp) {
console.log("request arrived.")
resp.writeHead(200, { 'Content-Type': 'application/json' });
resp.end("Hello world!!");
}).listen(3000);
每当我使用网址http://localhost:3000/
点击请求时,
它打印request arrived
消息两次。
我不知道,究竟是什么原因。 有些人请解释一下。
答案 0 :(得分:6)
浏览器很可能正在请求favicon.ico
文件。您可以通过打印URL来确认,如此
console.log("request arrived for URL", req.url);
当我在我的机器上尝试使用Chrome浏览器时,我得到了
request arrived for URL /
request arrived for URL /favicon.ico
如果您想避免这种情况,那么您需要特别处理favicon
请求。也许你可以做这样的事情,如here
if (req.url === '/favicon.ico') {
resp.writeHead(200, {'Content-Type': 'image/x-icon'} );
resp.end();
console.log('favicon requested');
return;
}
console.log("request arrived.")
resp.writeHead(200, { 'Content-Type': 'application/json' });
resp.end("Hello world!!");
答案 1 :(得分:0)
回答后续问题“我已经检查过了,但是我们如何避免呢?”答案是将前一个答案中的行放在具有http.createServer的行的正下方,这样您最终会得到类似以下的内容,其中包含4条添加到相关原始代码中的行:
great
/ \
gr eat
/ \ / \
g r e at
/ \
a t
[great, [gr, [g, r], eat, [e, at, [a, t]]]