Skip to content
This repository was archived by the owner on Mar 16, 2019. It is now read-only.

Commit b2f47bb

Browse files
committed
Fix XMLHttpRequest auto strategy
1 parent 0bf35df commit b2f47bb

File tree

3 files changed

+53
-27
lines changed

3 files changed

+53
-27
lines changed

src/index.js

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -254,14 +254,31 @@ class FetchBlobResponse {
254254
* @return {string} Decoded base64 string.
255255
*/
256256
this.text = ():string => {
257-
return decodeURIComponent(base64.decode(this.data))
257+
let res = this.data
258+
try {
259+
res = base64.decode(this.data)
260+
res = decodeURIComponent(res)
261+
} catch(err) {
262+
console.warn(err)
263+
res = ''
264+
}
265+
return res
258266
}
259267
/**
260268
* Convert result to JSON object.
261269
* @return {object} Parsed javascript object.
262270
*/
263271
this.json = ():any => {
264-
return JSON.parse(decodeURIComponent(base64.decode(this.data)))
272+
let res = this.data
273+
try {
274+
res = base64.decode(this.data)
275+
res = decodeURIComponent(res)
276+
res = JSON.parse(res)
277+
} catch(err) {
278+
console.warn(err)
279+
res = {}
280+
}
281+
return res
265282
}
266283
/**
267284
* Return BASE64 string directly.

src/ios/RNFetchBlobNetwork.m

Lines changed: 26 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -137,9 +137,11 @@ - (void) sendRequest:(__weak NSDictionary * _Nullable )options
137137

138138

139139
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
140-
if([options valueForKey:@"timeout"] != nil)
140+
float timeout = [options valueForKey:@"timeout"] == nil ? -1 : [[options valueForKey:@"timeout"] floatValue];
141+
NSLog(@"timeout = %f",timeout);
142+
if(timeout > 0)
141143
{
142-
defaultConfigObject.timeoutIntervalForRequest = [[options valueForKey:@"timeout"] floatValue]/1000;
144+
defaultConfigObject.timeoutIntervalForRequest = timeout/1000;
143145
}
144146
defaultConfigObject.HTTPMaximumConnectionsPerHost = 10;
145147
session = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:taskQueue];
@@ -196,21 +198,30 @@ - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dat
196198

197199
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
198200
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
201+
NSString * respType = @"";
199202
respStatus = statusCode;
200203
if ([response respondsToSelector:@selector(allHeaderFields)])
201204
{
202205
NSDictionary *headers = [httpResponse allHeaderFields];
203-
NSString * respType = [[RNFetchBlobReqBuilder getHeaderIgnoreCases:@"content-type"
206+
NSString * respCType = [[RNFetchBlobReqBuilder getHeaderIgnoreCases:@"Content-Type"
204207
fromHeaders:headers]
205208
lowercaseString];
206-
if([headers valueForKey:@"Content-Type"] != nil)
209+
if(respCType != nil)
207210
{
208211
NSArray * extraBlobCTypes = [options objectForKey:CONFIG_EXTRA_BLOB_CTYPE];
212+
if([respCType containsString:@"text/"])
213+
{
214+
respType = @"text";
215+
}
216+
else if([respCType containsString:@"application/json"])
217+
{
218+
respType = @"json";
219+
}
209220
// If extra blob content type is not empty, check if response type matches
210-
if( extraBlobCTypes != nil) {
221+
else if( extraBlobCTypes != nil) {
211222
for(NSString * substr in extraBlobCTypes)
212223
{
213-
if([[respType lowercaseString] containsString:[substr lowercaseString]])
224+
if([respCType containsString:[substr lowercaseString]])
214225
{
215226
respType = @"blob";
216227
respFile = YES;
@@ -219,14 +230,6 @@ - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dat
219230
}
220231
}
221232
}
222-
else if([respType containsString:@"text/"])
223-
{
224-
respType = @"text";
225-
}
226-
else if([respType containsString:@"application/json"])
227-
{
228-
respType = @"json";
229-
}
230233
else
231234
{
232235
respType = @"blob";
@@ -238,7 +241,7 @@ - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dat
238241
}
239242
}
240243
else
241-
respType = @"";
244+
respType = @"text";
242245
respInfo = @{
243246
@"taskId": taskId,
244247
@"state": @"2",
@@ -255,6 +258,8 @@ - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dat
255258
headers = nil;
256259
respInfo = nil;
257260
}
261+
else
262+
NSLog(@"oops");
258263

259264
if(respFile == YES)
260265
{
@@ -319,20 +324,20 @@ - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCom
319324
self.error = error;
320325
NSString * errMsg = [NSNull null];
321326
NSString * respStr = [NSNull null];
322-
NSString * respType = [respInfo valueForKey:@"respType"];
323327

324328
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
325-
if(error != nil)
326-
{
327-
errMsg = [error localizedDescription];
328-
}
329+
329330
if(respInfo == nil)
330331
{
331332
respInfo = [NSNull null];
332333
}
333334

335+
if(error != nil)
336+
{
337+
errMsg = [error localizedDescription];
338+
}
334339
// Fix #72 response with status code 200 ~ 299 considered as success
335-
if(respStatus> 299 || respStatus < 200)
340+
else if(respStatus> 299 || respStatus < 200)
336341
{
337342
errMsg = [NSString stringWithFormat:@"Request failed, status %d", respStatus];
338343
}

src/polyfill/XMLHttpRequest.js

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,9 @@ export default class XMLHttpRequest extends XMLHttpRequestEventTarget{
2323
_onreadystatechange : () => void;
2424

2525
upload : XMLHttpRequestEventTarget = new XMLHttpRequestEventTarget();
26-
static binaryContentTypes : Array<string> = [];
26+
static binaryContentTypes : Array<string> = [
27+
'image/', 'video/', 'audio/'
28+
];
2729

2830
// readonly
2931
_readyState : number = UNSENT;
@@ -145,7 +147,6 @@ export default class XMLHttpRequest extends XMLHttpRequestEventTarget{
145147
}
146148
else
147149
body = body ? body.toString() : body
148-
149150
this._task = RNFetchBlob
150151
.config({
151152
auto: true,
@@ -243,7 +244,6 @@ export default class XMLHttpRequest extends XMLHttpRequestEventTarget{
243244
}
244245

245246
_uploadProgressEvent(send:number, total:number) {
246-
console.log('_upload', this.upload)
247247
if(!this._uploadStarted) {
248248
this.upload.dispatchEvent('loadstart')
249249
this._uploadStarted = true
@@ -265,12 +265,16 @@ export default class XMLHttpRequest extends XMLHttpRequestEventTarget{
265265
}
266266

267267
_onError(err) {
268+
let statusCode = Math.floor(this.status)
269+
if(statusCode >= 100 && statusCode !== 408) {
270+
return
271+
}
268272
log.verbose('XMLHttpRequest error', err)
269273
this._statusText = err
270274
this._status = String(err).match(/\d+/)
271275
this._status = this._status ? Math.floor(this.status) : 404
272276
this._dispatchReadStateChange(XMLHttpRequest.DONE)
273-
if(err && String(err.message).match(/(timed\sout|timedout)/)) {
277+
if(err && String(err.message).match(/(timed\sout|timedout)/) || this._status == 408) {
274278
this.dispatchEvent('timeout')
275279
}
276280
this.dispatchEvent('loadend')

0 commit comments

Comments
 (0)