设想
我在 nodejs 上运行一个非常简单的服务器:
var http = require("http");
var ConnectionsNumber = 0;
function onRequest(request, response)
{
console.log((new Date).toUTCString() + " - Request received");
console.log(request.headers);
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Listening\n");
response.end();
ConnectionsNumber++;
console.log('Requests so far: ' + ConnectionsNumber);
}
http.createServer(onRequest).listen(8888);
console.log((new Date).toUTCString() + " - Server started");
但是当我启动服务器并发出请求(通过 Chrome)时,服务器一次收到两个请求。这是日志:
Wed, 03 Oct 2012 16:03:27 GMT - Server started
Wed, 03 Oct 2012 16:03:34 GMT - Request received
{ host: 'localhost:8888',
connection: 'keep-alive',
'cache-control': 'max-age=0',
'user-agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'accept-encoding': 'gzip,deflate,sdch',
'accept-language': 'it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4',
'accept-charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3' }
Requests so far: 1
Wed, 03 Oct 2012 16:03:34 GMT - Request received
{ host: 'localhost:8888',
connection: 'keep-alive',
accept: '*/*',
'user-agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4',
'accept-encoding': 'gzip,deflate,sdch',
'accept-language': 'it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4',
'accept-charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3' }
Requests so far: 2
问题
怎么了?
编辑
这是获胜者:
var http = require("http");
var ConnectionsNumber = 0;
function onRequest(request, response)
{
console.log((new Date).toUTCString() + " - Request received");
console.log(request.url);
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Listening\n");
response.end();
ConnectionsNumber++;
console.log('Requests so far: ' + ConnectionsNumber);
}
http.createServer(onRequest).listen(8888);
console.log((new Date).toUTCString() + " - Server started");
以及相应的日志:
Wed, 03 Oct 2012 20:00:04 GMT - Server started
Wed, 03 Oct 2012 20:00:14 GMT - Request received
/
Requests so far: 1
Wed, 03 Oct 2012 20:00:14 GMT - Request received
/favicon.ico
Requests so far: 2
这就是所有人。