Как разобрать ответ `chunked` по символу разделения? - PullRequest
1 голос
/ 28 июня 2019

У меня есть бэкэнд API с частичным ответом. Каждый чанк - массив объектов json, оканчивающийся новой строкой \n.

В браузере я делаю запрос по нажатию кнопки:

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 голосов
/ 04 июля 2019

Я нашел решение с https://github.com/eBay/jsonpipe, которое "буферизует" данные для допустимого json. Delimeter настраивается, в моем случае \n:

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