2016-03-21 104 views
0

我是node.js的新手,在線學習教程。 我嘗試了下面的一段代碼:nodejs - 爲什麼我的異步函數運行兩次?

var http = require("http"); 

// create a server 
http.createServer(function(req, res) { 
    console.log("Received Request"); 
    res.writeHead(200, {'Content-Type':'application/json'}); 
    res.end("{'status':'200', 'message':'Hello World'}"); 
    console.log("Response Sent"); 
}).listen(process.env.PORT, process.env.IP); 

我確實收到正確的響應,但在控制檯輸出爲:

Received Request 
Response Sent 
Received Request 
Response Sent 

我想知道爲什麼我的代碼運行兩次?我犯了一些錯誤嗎? 請幫忙!!

+6

你碰巧刷新頁面或訪問它兩次? – David

+0

不,我只是從我的瀏覽器地址欄打一次網址! –

+3

這幾乎可以肯定是由於瀏覽器對favicon資源發出第二個請求。嘗試'console.log(「Received Request」,req.url);' – apsillers

回答

2

當您使用瀏覽器訪問網址時,瀏覽器會發送一個favicon請求,然後發送另一個內容請求,這就是爲什麼您會看到兩個請求!

使用PostMan並請求相同的網址,您應該只會看到一個請求。

3

調試的最好的辦法就是查詢的網址

var http = require("http"); 

// create a server 
http.createServer(function(req, res) { 
    console.log(req.url);//add this line, I hope it will help 
    console.log("Received Request"); 
    res.writeHead(200, {'Content-Type':'application/json'}); 
    res.end("{'status':'200', 'message':'Hello World'}"); 
    console.log("Response Sent"); 
}).listen(process.env.PORT, process.env.IP); 

另外,作爲巴薩姆Rubaye指出,它可能最有可能是由於你的情況圖標

+0

+的答案,教你如何自己診斷問題。 – jfriend00