我對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
所以我只是用javascript創建一個htnl頁面,它會週期性地發送ajax調用到node.js webserver,它會返回json數據,我可以在客戶端渲染? – darewreck
是的,'/ getChatData'路由只會返回當前數據並且有一個運行javascript的html頁面來定期請求這個路由。 – djbrick