var http = require('http');
http.createServer(function(req,res){
res.writeHead(200,{'Content-Type' : 'text/html'});
res.write('<h1>Node.js</h1>');
console.log("running...");
res.end('<p>Hello World!!</p>');
}).listen(3000);
console.log("HTTP server is listening at port 3000.");
运行结果发现每次访问,后台会出现两条running信息。
这是因为访问完之后,浏览器还会去访问/favicon.ico,在实际调试过程中两次访问会给我们调试带来麻烦还有许多问题,所以我们要防止他进行第二次的访问。代码如下:
var http = require('http');
http.createServer(function(req,res){
res.writeHead(200,{'Content-Type' : 'text/html'});
if(req.url !== "/favicon.ico"){//清楚第二次访问
res.write('<h1>Node.js</h1>');
console.log("running...");
res.end('<p>Hello World!!</p>');//不写则没有http协议尾,但会产生两次访问
}
}).listen(3000);
console.log("HTTP server is listening at port 3000.");
这样每次访问,后台只会输出一条running信息了。
本文介绍如何使用Node.js快速搭建一个简单的HTTP服务器,并通过代码示例讲解如何避免浏览器默认请求/favicon.ico图标导致的重复日志输出。
951

被折叠的 条评论
为什么被折叠?



