首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过拆分符号解析`chunked`响应?

如何通过拆分符号解析`chunked`响应?
EN

Stack Overflow用户
提问于 2019-06-28 21:46:22
回答 1查看 362关注 0票数 1

我有一个带有分块响应的后端api。每个chunk - json对象数组,以新行\n结束。

在浏览器中,我在单击按钮时发出请求:

代码语言:javascript
复制
searchBtn.onclick = function () {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", "/api/p2p_search" + text, true);
            xhr.onprogress = function () {
                var searchArray = JSON.parse(xhr.responseText);
                //show array in result
            };
            xhr.send();
        };

但有时一个有效的json数组块我会收到多个块,所以我无法解析它。例如:[{"hello":"world"}]

有没有一种方法可以真正地接收按行拆分的块,或者另一种接收分块响应的方法?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-05 02:49:22

我找到了https://github.com/eBay/jsonpipe的解决方案,它可以将数据“缓冲”到有效的json中。定界器可配置,在我的例子中是\n

代码语言:javascript
复制
  <script src="jsonpipe.js"></script>

  var jsonpipe = require('jsonpipe');
    /**
     * @param {String} url A string containing the URL to which the request is sent.
     * @param {Object} url A set of key/value pairs that configure the Ajax request.
     * @return {XMLHttpRequest} The XMLHttpRequest object for this request.
     * @method flow
     */
    jsonpipe.flow('http://api.com/items?q=batman', {
        "delimiter": "\n", // String. The delimiter separating valid JSON objects; default is "\n\n"
        "onHeaders": function(statusText, headers) {
            // Do something with the headers and the statusText.
        }
        "success": function(data) {
            // Do something with this JSON chunk
        },
        "error": function(errorMsg) {
            // Something wrong happened, check the error message
        },
        "complete": function(statusText) {
            // Called after success/error, with the XHR status text
        },
        "timeout": 3000, // Number. Set a timeout (in milliseconds) for the request
        "method": "GET", // String. The type of request to make (e.g. "POST", "GET", "PUT"); default is "GET"
        "headers": { // Object. An object of additional header key/value pairs to send along with request
            "X-Requested-With": "XMLHttpRequest"
        },
        "data": "", // String. A serialized string to be sent in a POST/PUT request,
        "withCredentials": true // Boolean. Send cookies when making cross-origin requests; default is true
    });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56808143

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档