【问题标题】:Streaming Node.js response to client over XHR通过 XHR 将 Node.js 响应流式传输到客户端
【发布时间】:2016-06-28 06:26:03
【问题描述】:

我有一个 Express.js 服务器,其路由负责解析和导入 CSV 文件。

我想将导入过程的状态实时报告回用户的浏览器。

来自 Express.js 的流式响应非常简单:

router.get( '/test', function( _req, _res, _next ) {
    _res.write( 'File import initiated.' );

    // ... processing CSV in loop

    _res.write( 'Processing row x.' );

    // artificial delay to simulate some i/o
    setTimeout( function() {
        _res.write( 'File import completed successfully.' );
        _res.end();
    }, 2000 )
} );

通过 CURL 向端点发送 HTTP 请求按预期工作。在上面的示例中,两个流式响应 立即收到,两秒后有最终响应。

但在浏览器 (Chrome) 中情况并非如此。 使用 jQuery $.ajax 和原始 XHR 调用进行测试,整个 响应完成后,响应似乎被缓冲并立即返回。

通常如何处理这种类型的通信?我认为 socket.io 是一个选项,但肯定有一个更简单的 如何利用浏览器的 build int XHR 或 XHR2 功能?

【问题讨论】:

标签: javascript jquery node.js express socket.io


【解决方案1】:

您可以向客户端返回一个参考 ID,客户端调用正确的 http api 来收集该 csv 处理请求的状态。您可能需要一些后端支持来启用此功能。类似于数据库中可以跟踪此状态的某些表。

router.get( '/test', function( _req, _res, _next ) {
    SaveFile(_res.file).then(function(id) {
        _res.end(JSON.stringify({id: id});
    });
});

router.get( '/status', function( _req, _res, _next ) {
    GetStatus(_res.params.id).then(function(status) {
        _res.end(JSON.stringify(status));
    });
});

否则,如果您仍然想要实时,请使用 websockets。你必须设计你期望的沟通形式。

【讨论】:

  • 好主意。我决定使用 websockets 进行实时数据推送。
猜你喜欢
  • 2023-03-02
  • 1970-01-01
  • 2020-01-31
  • 2014-12-21
  • 2018-07-15
  • 1970-01-01
  • 1970-01-01
  • 2015-11-29
  • 2014-12-06
相关资源
最近更新 更多