您的位置:首页 > Web前端 > Node.js

Node.js HelloWorld的小细节

2017-10-01 11:00 585 查看
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