客户端两次向服务器发送请求? [英] Client is sending request twice to server?
问题描述
我对服务器和节点非常陌生.我创建了一个非常基本的httpserver,并尝试在控制台上打印连接数.下面是相同的代码
I am very new to servers and node. I created a very basic httpserver and trying to print number of connection on console. Below is the code for the same
var count = 0;
var http = require("http");
var server = http.createServer(function(request,response){
response.writeHead(200, {"Content-Type": "text/html"});
count++;
console.log('Count' + count);
response.end(count + '');
});
server.listen(8080);
console.log("Server is listening");
三个连接的计数值增加到6之后.请让我知道为什么每个http请求的计数都增加2.
After three connection count value is incremented upto 6. Please let me know why there is a increment of 2 count for every http request
推荐答案
您的浏览器可能会请求其他URL,例如favicon.ico,许多浏览器都会这样做,以便找到一个可以显示为小图标的小图标.网站的表示形式.
Your browser is likely requesting other URLs such as a favicon.ico which is something many browsers will do in order to find a small icon that it can display as a representation of the site.
为此,您可以检查 request.url
以查找特定路径,并且仅在该路径是您期望的路径时才应用逻辑.
To defend against that, you can check request.url
for a specific path and only apply your logic if the path is what you expect.
这是您可以做到这一点的一种方法:
Here's one way you could do that:
var count = 0;
var http = require("http");
var server = http.createServer(function(request,response){
if (request.url === "/") {
response.writeHead(200, {"Content-Type": "text/html"});
count++;
console.log('Count' + count);
response.end(count + '');
} else {
response.writeHead(404, {"Content-Type": "text/html"});
response.write("Content not found");
response.end();
}
});
server.listen(8080);
console.log("Server is listening");
这篇关于客户端两次向服务器发送请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!