递增运算符添加两个

我有以下的node.js程序:

var http = require("http"); var count = 0; http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World: " + yolo()); response.end(); }).listen(8888); function yolo(){ count++; return count; } 

我在terminal窗口中运行程序,并通过我的浏览器在http:// localhost:8888 /

刷新时我得到以下输出:

  • 世界您好:1
  • Hello World:3
  • Hello World:5
  • 世界你好:7
  • 世界您好:9
  • 等等…

为什么程序每次增加countvariables而不是一个?

您可以检查浏览器何时调用/favicon.ico

 http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); if (request.url !== '/favicon.ico') { response.write("Hello World: " + yolo()); } response.end(); }).listen(8888); 

你可能想使用像express这样的路由库来给你想要的东西。

 var express = require('express'); var app = express(); var count = 0; app.get('/', function(req, res){ count++; res.send('Hello world:'+count); }); app.listen(3000); 

这只会响应“/”的请求,而不是像createServer那样的每个URL。