2015-07-20 175 views
1

我有以下的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; 
} 

我在http://localhost:8888/

運行在通過我的瀏覽器終端窗口,並訪問它的程序我得到的,因爲我輸出以下刷新:

  • 的Hello World:1
  • 的Hello World:3
  • 的Hello World:5
  • 的Hello World:7
  • 的Hello World:9
  • 等...

爲什麼計劃通過增加每次兩,而不是一個計數變量?

+2

您確定沒有發生增加它的其他請求嗎?把'console.log'放在'yolo'裏面 – tymeJV

+5

很可能有一個'favicon.ico'的請求。 –

+0

我的猜測是,每次刷新瀏覽器時,它都會向服務器發出兩個請求。嘗試記錄到一個文件,包括來自請求標題的細節,如「日期」和「方法」。 –

回答

3

瀏覽器發出呼籲/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); 
+0

問題是,即使一個人不存在,chrome總是會請求favicon.ico。在google-fu之後,我發現它是一個常見的投訴。總之,這個解決方案是有效的。謝謝。 – mstagg

2

你可能想使用路由庫是要快給你想要的東西。

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會做的請求。