如何通过分割符号解析“块状”响应?

时间:2019-06-28 13:46:22

标签: javascript chunked-encoding

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

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

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"}]

是不是有一种方法可以真正接收按行分割的数据块,或者有另一种方法可以接收分块的响应?

1 个答案:

答案 0 :(得分:0)

我找到了https://github.com/eBay/jsonpipe的解决方案,该解决方案将数据“缓冲”到有效的json。在我的情况下,\n可以配置Delimeter:

  <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
    });