2013-09-27 70 views
3

我想運行一個簡單的應用程序,檢查使用HTTP服務器模塊的URL的狀態。Node.js - 如何檢查HTTP請求中的URL的狀態

基本上,這是一個簡單的HTTP服務器:

require('http').createServer(function(req, res) { 
     res.writeHead(200, {'Content-Type': 'text/html'}); 
     res.end('URL is OK'); 
    }).listen(4000); 

現在內,我要檢查使用本節中的URL的狀態:

var request = require('request'); 
request('http://www.google.com', function (error, response, body) { 
    if (!error && response.statusCode == 200) { 
    console.log("URL is OK") // Print the google web page. 
    } 
}) 

所以基本上我要啓動節點,打開瀏覽器並顯示帶有「URL可以」的文字內容。然後每10分鐘刷新一次。

任何幫助,非常感謝。

回答

10

帶節點的常規策略是,您必須在回調中放置任何取決於異步操作結果的內容。在這種情況下,這意味着等待發送你的迴應,直到你知道谷歌是否升起。

爲每10分鐘刷新,您將需要編寫一些代碼放到網頁中投放,可能或者使用<meta http-equiv="refresh" content="30">(30秒),或在Preferred method to reload page with JavaScript?

var request = require('request'); 
function handler(req, res) { 
    request('http://www.google.com', function (error, response, body) { 
    if (!error && response.statusCode == 200) { 
     console.log("URL is OK") // Print the google web page. 
     res.writeHead(200, {'Content-Type': 'text/html'}); 
     res.end('URL is OK'); 
    } else { 
     res.writeHead(500, {'Content-Type': 'text/html'}); 
     res.end('URL broke:'+JSON.stringify(response, null, 2)); 
    } 
    }) 
}; 

require('http').createServer(handler).listen(4000); 
+0

的JavaScript的技術之一,非常感謝您對這個例。它可以工作,但是,我發現如果HTTP狀態動態地從200改變到500,那麼它不刷新頁面。您必須重新啓動http服務器。有沒有辦法刷新操作? – lia1000

+0

您需要在發送的HTML中包含頁面刷新代碼,這兩個響應(200個案例和200個案例)。 – Plato