Handle Xmlhttprequest Response With Large Data
Using Chrome, I setup a XMLHttpRequest: const xhr = new XMLHttpRequest(); xhr.open(method, url, true); ... xhr.onreadystatechange = () => { if (xhr.readyState === XMLHttpReq
Solution 1:
You can try using the Fetch API, an improved version of the XMLHttpRequest using directly promises. It comes with a feature to stream the response body instead of buffering the whole body response as text.
Basically, using the progress
event, you are called on each chunk but the xhr response keeps accumulating the response as text thus reaching memory limit.
With the Fetch API
, you can read the received bytes as they arrive:
const consume = responseReader => {
return responseReader.read().then(result => {
if (result.done) { return; }
// do something with the current chunkconst chunk = result.value;
return consume(responseReader);
});
}
// Perform the request and consume response stream
fetch(url).then(response => {
return consume(response.body.getReader());
})
.catch(console.log.bind(console));
For more information see this article: Fetch (or the undeniable limitations of XHR)
Streaming the response body through Fetch API is only supported since Chrome 43, and Edge 14 at the time of writing. Cf compatibility table.
Post a Comment for "Handle Xmlhttprequest Response With Large Data"