初接触nodejs,第一步就遇到问题
var http = require('http');
http.createServer(function (req, res) {
console.log(req.headers['user-agent'])
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
这么一段简单的代码,为什么每次访问都是输出两次
Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)
Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)
很郁闷,难道一次请求,触发两次request事件?
7 回复
看了文档的解释似乎是这样
Emitted each time there is a request. Note that there may be multiple requests per connection (in the case of keep-alive connections)
不过这样不太靠谱啊?一次连接多次请求,求解释。
你加上 timestamp 试试。我运行你的代码没出问题。
$ node test21.js
Wget/1.13.4 (linux-gnu)
$ wget http://127.0.0.1:1337
--2013-04-26 10:47:56-- http://127.0.0.1:1337/
Connecting to 127.0.0.1:1337... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/plain]
Saving to: `index.html'
[ <=> ] 12 --.-K/s in 0s
2013-04-26 10:47:56 (390 KB/s) - `index.html' saved [12]
@leapon 郁闷了,时间不一样。
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31Fri Apr 26 2013 22:55:37 GMT+0800 (中国标准时间)
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31Fri Apr 26 2013 22:55:38 GMT+0800 (中国标准时间)
我这边一次访问出现了3次。。。
有的浏览器会自动发起对favo.ico的请求.
var http = require('http');
http.createServer(function (req, res) {
console.log(req.url+ new Date().getTime())
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
原来是浏览器会自动请求favicon ,而wget不会,所以触发了两次。
学习了。