2013-09-24 76 views
0

我對node.js非常陌生,所以如果我犯了一個明顯的錯誤,請耐心等待。Node.js和理解響應如何工作

爲了理解node.js,我試圖創建一個基本上如下的web服務器: 1)每次訪問根url(localhost:8000 /)時,更新頁面並添加「hello world」。 2)用戶可以去到另一個URL(本地主機:8000/getChatData),它會顯示從URL中建立起來的所有數據(本地主機:8000 /)被觸發

問題我遇到: 1)I在呈現的頁面上顯示該數據時遇到問題。我有一個計時器應該隨時調用get_data(),並使用存儲附加輸出的數據變量更新屏幕。具體來說,這行下面response.simpleText(200,數據);工作不正常。

文件

// Load the node-router library by creationix 
var server = require('C:\\Personal\\ChatPrototype\\node\\node-router').getServer(); 

var data = null; 
// Configure our HTTP server to respond with Hello World the root request 
server.get("/", function (request, response) { 
    if(data != null) 
    { 
     data = data + "hello world\n"; 
    } 
    else 
    { 
     data = "hellow world\n"; 
    } 
    response.writeHead(200, {'Content-Type': 'text/plain'}); 
    console.log(data); 
    response.simpleText(200, data); 
    response.end(); 

}); 

// Configure our HTTP server to respond with Hello World the root request 
server.get("/getChatData", function (request, response) { 
    setInterval(function() { get_data(response); }, 1000); 

}); 

function get_data(response) 
{ 
    if(data != null) 
    { 
     response.writeHead(200, {'Content-Type': 'text/plain'}); 

     response.simpleText(200, data); 
     console.log("data:" + data); 
      response.end(); 
    } 
    else 
    { 
     console.log("no data"); 
    } 
} 

// Listen on port 8080 on localhost 
server.listen(8000, "localhost"); 

如果有更好的方式來做到這一點,請讓我知道。目標是讓服務器調用url來更新變量,並有另一個html頁面每秒動態報告/顯示更新的數據。

謝謝, d

回答

0

客戶服務器模型的工作由客戶端向服務器發送的請求,並且作爲回報服務器發送的響應。服務器無法向客戶端發送對客戶端沒有要求的響應。客戶端啓動請求。因此,您不能讓服務器按時間間隔更改響應對象。

客戶端將不會獲取這些請求的更改。通常如何處理這樣的事情,通過AJAX來自服務器的初始響應將Javascript代碼發送給在一段時間內向服務器發起請求的客戶端。

+0

所以我只是用javascript創建一個htnl頁面,它會週期性地發送ajax調用到node.js webserver,它會返回json數據,我可以在客戶端渲染? – darewreck

+0

是的,'/ getChatData'路由只會返回當前數據並且有一個運行javascript的html頁面來定期請求這個路由。 – djbrick

0

setTimeout接受沒有參數的函數,這是顯而易見的,因爲它會在以後執行。您在該功能中需要的所有值都應該在該時間點可用。在您的情況下,您嘗試通過的response對象是本地實例,它只在server.get的回調(您設置setTimeout)的範圍內有作用域。

有幾種方法可以解決此問題。您可以將響應實例的副本保留在get_data所屬的外部範圍中,或者您可以將get_data完全移入並刪除setTimeout。不推薦第一種解決方案,就好像在1秒內多次調用getChatData,最後的副本將佔優勢。

但我的建議是將data保留在數據庫中,並顯示一次getChatData被調用。