Skip to content
Permalink
Browse files
Transform empty responses into empty Blobs
Summary:
In `XMLHttpRequest`, if the responseType is `Blob`, but the response is an empty string, we return `null` from `XMLHttpRequest.prototype.response()`. Instead, we should return an empty Blob. This is the behaviour on the web. To demonstrate, run the following HTTP server with Node:

## server.js
```
const http = require('http');
const server = http.createServer();

server.on('request', (request, response) => {
  if (request.url.includes('img.png')) {
    console.log('sending image');
    response.end('');
    return;
  }

  response.end('Hello World!');
});

server.listen('9000');
```

Then, open up a web browser to `http://localhost:9000`, and type the following in the console:

```
var oReq = new XMLHttpRequest();
oReq.open('GET', 'http://localhost:9000/img.png', true);
oReq.responseType = 'blob';

oReq.onload = function(oEvent) {
  var blob = oReq.response;
  console.warn(blob);
};

oReq.onerror = function(error) {
  console.warn('Error!');
};

oReq.send();
```

This warns:
```
Blob {size: 0, type: "text/xml"}
```

Changelog:
[Both][Fixed] - [RN][XMLHttpRequest] Transform empty responses into empty Blobs

Reviewed By: sahrens

Differential Revision: D19500607

fbshipit-source-id: ec35e534b32a507c8a94a29e955b7bc4c62902a0
  • Loading branch information
RSNara authored and facebook-github-bot committed Jan 27, 2020
1 parent aeaf286 commit 9a8c06b502c774f7a0bff1bdc064fbfe16ca75be
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
@@ -85,9 +85,15 @@ class FileReader extends (EventTarget(...READER_EVENTS): any) {
throw new Error('FileReader.readAsArrayBuffer is not implemented');
}

readAsDataURL(blob: Blob) {
readAsDataURL(blob: ?Blob) {
this._aborted = false;

if (blob == null) {
throw new TypeError(
"Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'",
);
}

NativeFileReaderModule.readAsDataURL(blob.data).then(
(text: string) => {
if (this._aborted) {
@@ -106,9 +112,15 @@ class FileReader extends (EventTarget(...READER_EVENTS): any) {
);
}

readAsText(blob: Blob, encoding: string = 'UTF-8') {
readAsText(blob: ?Blob, encoding: string = 'UTF-8') {
this._aborted = false;

if (blob == null) {
throw new TypeError(
"Failed to execute 'readAsText' on 'FileReader': parameter 1 is not of type 'Blob'",
);
}

NativeFileReaderModule.readAsText(blob.data, encoding).then(
(text: string) => {
if (this._aborted) {
@@ -244,7 +244,7 @@ class XMLHttpRequest extends (EventTarget(...XHR_EVENTS): any) {
if (typeof this._response === 'object' && this._response) {
this._cachedResponse = BlobManager.createFromOptions(this._response);
} else if (this._response === '') {
this._cachedResponse = null;
this._cachedResponse = BlobManager.createFromParts([]);
} else {
throw new Error(`Invalid response for blob: ${this._response}`);
}

0 comments on commit 9a8c06b

Please sign in to comment.