2013-09-24 35 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被调用。