我对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