为什么node.js脚本调用两次?

我是Node.js的初学者,我在Node.js中编写第一个脚本,如下所示:

var count = 0; var http = require('http'); var serv = http.createServer(function (req, res) { count++; console.log("why two?:" + count); res.writeHead(200,{'Content-Type': 'text/html'}); require('colors'); if (count % 2 == 0) { console.log('count:' + count); console.log('smashing node'.rainbow); res.end('<marquee>Smashing Node</marquee>'); } else { console.log('count:' + count); console.log('WTF'.rainbow); res.end('<h4>Smashing Node</h4>'); } }); serv.listen(3000); 

然后我运行这个脚本

节点first.js

在浏览器中,访问http:// localhost:3000而在控制台中的结果是:

 why two?:1 count:1 WTF why two?:2 count:2 smashing node 

为什么代码被调用两次? 谢谢

因为有两个请求正在进行。

可能一个是/而另一个是/favicon.ico

你的代码并不关心处理请求时的path。

您可以通过查看浏览器的开发人员工具的Net选项卡或检查req对象的内容来testing。

每当你在http:// localhost:3000上请求匿名函数时,

所以也许不知何故,你要求两次(例如/和/favicon.ico)尝试打开铬开发工具,并在控制台选项卡,你可能会看到一个错误,favicon.ico没有find。

或者你可以用摩根来跟踪请求:

 var app = require('express')(); var morgan = require('morgan'); app.use(morgan('dev')); 

它会logging每个请求,代码和URL-s。 它需要expression。

 var count = 0; var http = require('http'); var serv = http.createServer(); serv.on('request',function(req,res){ count++; console.log("why two?:" + count); res.writeHead(200,{'Content-Type': 'text/html'}); if (req.url=='/') { console.log(req.method); console.log(req.headers); console.log(req.url); res.end('<marquee>Smashing Node</marquee>'); } }); serv.listen(3000); 

在这个它只检查'/'url,然后回应….所以选框被返回