help? 为何node.js程序中每次访问,则number是加二?
发布于 9 年前 作者 jiangwest 4222 次浏览 最后一次编辑是 8 年前 来自 问答

每次网页 127.0.0.1:3000 被访问,number值+2,而不是+1? for example: number 显示 2,4,6,…

node程序如下


  /**
   * New node file
   */
  var http=require('http');
  var localTime=new Date();
  var number =0;
  
  http.createServer(function(req,res){
	  res.writeHead(200,{'Content-Type':'text/html'});
	  res.write('<h1>Node.js</h1>');
	  res.end('<p>Hello World, you are the ' +  number + ' vistior! </p>');
	  
	  req.on('end',function(){
		  number++;
		  console.log("this webpage is accessed!");
		  console.log(localTime.toLocaleString());
	  });	
	  
  }).listen(3000);

有何问题?

10 回复

favicon 吧

console.log(req.url);
number++;前面加上上面那句话就知道为什么了…

抢得都太快, 完全没跟上。

thanks! 是favicon.ico请求所导致

  • / 表示用户输入的客户端请求的目标URL地址,"/"代表用户的目标url地址为web应用程序的根目录.
  • /favicon.ico表示为浏览器为页面在收藏夹中的显示图标.默认为favicon.ico.而自动发出的请求的目标URL地址. 我改为
  /**
   * New node file
   */
  var http=require('http');
  var localTime=new Date();
  var number =0;
  
  http.createServer(function(req,res){
	  res.writeHead(200,{'Content-Type':'text/html'});
	  res.write('<h1>Node.js</h1>');
	  res.end('<p>Hello World, you are the ' +  number + ' vistior! </p>');
	  
	  req.on('end',function(){
		  console.log(req.url);
		  if(req.url !== '/favicon.ico'){
			  //todo
			  number++;
			  console.log("this webpage is accessed!");
			  console.log(localTime.toLocaleString());
			  
		  }		
	  });	
	  
  }).listen(3000);

@captainblue2013 好不容易看到一个以我的智商和才华能答上来的帖子!你们能不能让我!

这样写的话会对所有请求+1,favicon也会请求一次哦

哈哈 每个初学的都会碰到的坑

这个帖子 回答的都是大神,除了我

回到顶部