1

我想做类似的事情:

//client -> notifies server that client is connected.

//server -> begins fetching information from DB (series of both async and synchronous requests).

//as sets of data become available on server -> server pushes updates to client via res.render()

基本上我在客户端上有一个菜单项,我想在服务器获取的数据准备好时更新该菜单。有什么办法吗?我注意到我做不到

res.render('something');
// again
res.render('somethingElse');

因为一旦调用了render,就发送了response,不能再次调用render

“错误:发送后无法设置标题。”

有什么建议么?

4

2 回答 2

3

您可能会从使用 WebSockets 中受益:

http://en.wikipedia.org/wiki/WebSocket

这篇文章有一点信息:

哪个 websocket 库与 Node.js 一起使用?

于 2013-08-26T00:00:13.893 回答
2

HTTP works via request/response. Typically once the response is sent, the connection is terminated.

To stream data from the server to client, you can use websockets. There is a very popular node.js module called socket.io, which simplifies using websockets.

Using socket.io, the client code would look like this:

var socket = io.connect('http://yourserver.com');
socket.on('data', function (data) {
    updateMenu(data);
});

And the server code:

var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
    socket.emit('data', data);
    getMoreDataFromDb(function(data){
        socket.emit('data', data);
    });
    // etc..
});

Alternatively, if you want a simpler solution, you can just make multiple small ajax requests to the server, until you get all your data:

(function getData(dataId){ 

    $.ajax({
        url:"yourserver.com/getdata",
        data: dataId || {},
        success:function(data){
            updateMenu(data);
            if(data) getData({ lastDataReceived: data.lastId }); // server is still returning data, request more
        }
    });

})();
于 2013-08-26T01:06:03.517 回答