ソースを参照

Fix XMLHttpRequest auto strategy

Ben Hsieh 7 年 前
コミット
b2f47bb657
共有3 個のファイルを変更した53 個の追加27 個の削除を含む
  1. 19
    2
      src/index.js
  2. 26
    21
      src/ios/RNFetchBlobNetwork.m
  3. 8
    4
      src/polyfill/XMLHttpRequest.js

+ 19
- 2
src/index.js ファイルの表示

254
      * @return {string} Decoded base64 string.
254
      * @return {string} Decoded base64 string.
255
      */
255
      */
256
     this.text = ():string => {
256
     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
258
     }
266
     }
259
     /**
267
     /**
260
      * Convert result to JSON object.
268
      * Convert result to JSON object.
261
      * @return {object} Parsed javascript object.
269
      * @return {object} Parsed javascript object.
262
      */
270
      */
263
     this.json = ():any => {
271
     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
265
     }
282
     }
266
     /**
283
     /**
267
      * Return BASE64 string directly.
284
      * Return BASE64 string directly.

+ 26
- 21
src/ios/RNFetchBlobNetwork.m ファイルの表示

137
 
137
 
138
     
138
     
139
     NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
139
     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)
141
     {
143
     {
142
-        defaultConfigObject.timeoutIntervalForRequest = [[options valueForKey:@"timeout"] floatValue]/1000;
144
+        defaultConfigObject.timeoutIntervalForRequest = timeout/1000;
143
     }
145
     }
144
     defaultConfigObject.HTTPMaximumConnectionsPerHost = 10;
146
     defaultConfigObject.HTTPMaximumConnectionsPerHost = 10;
145
     session = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:taskQueue];
147
     session = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:taskQueue];
196
  
198
  
197
     NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
199
     NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
198
     NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
200
     NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
201
+    NSString * respType = @"";
199
     respStatus = statusCode;
202
     respStatus = statusCode;
200
     if ([response respondsToSelector:@selector(allHeaderFields)])
203
     if ([response respondsToSelector:@selector(allHeaderFields)])
201
     {
204
     {
202
         NSDictionary *headers = [httpResponse allHeaderFields];
205
         NSDictionary *headers = [httpResponse allHeaderFields];
203
-        NSString * respType = [[RNFetchBlobReqBuilder getHeaderIgnoreCases:@"content-type"
206
+        NSString * respCType = [[RNFetchBlobReqBuilder getHeaderIgnoreCases:@"Content-Type"
204
                                                                fromHeaders:headers]
207
                                                                fromHeaders:headers]
205
                                lowercaseString];
208
                                lowercaseString];
206
-        if([headers valueForKey:@"Content-Type"] != nil)
209
+        if(respCType != nil)
207
         {
210
         {
208
             NSArray * extraBlobCTypes = [options objectForKey:CONFIG_EXTRA_BLOB_CTYPE];
211
             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
+            }
209
             // If extra blob content type is not empty, check if response type matches
220
             // If extra blob content type is not empty, check if response type matches
210
-            if( extraBlobCTypes !=  nil) {
221
+            else if( extraBlobCTypes !=  nil) {
211
                 for(NSString * substr in extraBlobCTypes)
222
                 for(NSString * substr in extraBlobCTypes)
212
                 {
223
                 {
213
-                    if([[respType lowercaseString] containsString:[substr lowercaseString]])
224
+                    if([respCType containsString:[substr lowercaseString]])
214
                     {
225
                     {
215
                         respType = @"blob";
226
                         respType = @"blob";
216
                         respFile = YES;
227
                         respFile = YES;
219
                     }
230
                     }
220
                 }
231
                 }
221
             }
232
             }
222
-            else if([respType containsString:@"text/"])
223
-            {
224
-                respType = @"text";
225
-            }
226
-            else if([respType containsString:@"application/json"])
227
-            {
228
-                respType = @"json";
229
-            }
230
             else
233
             else
231
             {
234
             {
232
                 respType = @"blob";
235
                 respType = @"blob";
238
             }
241
             }
239
         }
242
         }
240
         else
243
         else
241
-            respType = @"";
244
+            respType = @"text";
242
         respInfo = @{
245
         respInfo = @{
243
                      @"taskId": taskId,
246
                      @"taskId": taskId,
244
                      @"state": @"2",
247
                      @"state": @"2",
255
         headers = nil;
258
         headers = nil;
256
         respInfo = nil;
259
         respInfo = nil;
257
     }
260
     }
261
+    else
262
+        NSLog(@"oops");
258
 
263
 
259
     if(respFile == YES)
264
     if(respFile == YES)
260
     {
265
     {
319
     self.error = error;
324
     self.error = error;
320
     NSString * errMsg = [NSNull null];
325
     NSString * errMsg = [NSNull null];
321
     NSString * respStr = [NSNull null];
326
     NSString * respStr = [NSNull null];
322
-    NSString * respType = [respInfo valueForKey:@"respType"];
323
     
327
     
324
     [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
328
     [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
325
-    if(error != nil)
326
-    {
327
-        errMsg = [error localizedDescription];
328
-    }
329
+    
329
     if(respInfo == nil)
330
     if(respInfo == nil)
330
     {
331
     {
331
         respInfo = [NSNull null];
332
         respInfo = [NSNull null];
332
     }
333
     }
333
     
334
     
335
+    if(error != nil)
336
+    {
337
+        errMsg = [error localizedDescription];
338
+    }
334
     // Fix #72 response with status code 200 ~ 299 considered as success
339
     // Fix #72 response with status code 200 ~ 299 considered as success
335
-    if(respStatus> 299 || respStatus < 200)
340
+    else if(respStatus> 299 || respStatus < 200)
336
     {
341
     {
337
         errMsg = [NSString stringWithFormat:@"Request failed, status %d", respStatus];
342
         errMsg = [NSString stringWithFormat:@"Request failed, status %d", respStatus];
338
     }
343
     }

+ 8
- 4
src/polyfill/XMLHttpRequest.js ファイルの表示

23
   _onreadystatechange : () => void;
23
   _onreadystatechange : () => void;
24
 
24
 
25
   upload : XMLHttpRequestEventTarget = new XMLHttpRequestEventTarget();
25
   upload : XMLHttpRequestEventTarget = new XMLHttpRequestEventTarget();
26
-  static binaryContentTypes : Array<string> = [];
26
+  static binaryContentTypes : Array<string> = [
27
+    'image/', 'video/', 'audio/'
28
+  ];
27
 
29
 
28
   // readonly
30
   // readonly
29
   _readyState : number = UNSENT;
31
   _readyState : number = UNSENT;
145
     }
147
     }
146
     else
148
     else
147
       body = body ? body.toString() : body
149
       body = body ? body.toString() : body
148
-
149
     this._task = RNFetchBlob
150
     this._task = RNFetchBlob
150
                   .config({
151
                   .config({
151
                     auto: true,
152
                     auto: true,
243
   }
244
   }
244
 
245
 
245
   _uploadProgressEvent(send:number, total:number) {
246
   _uploadProgressEvent(send:number, total:number) {
246
-    console.log('_upload', this.upload)
247
     if(!this._uploadStarted) {
247
     if(!this._uploadStarted) {
248
       this.upload.dispatchEvent('loadstart')
248
       this.upload.dispatchEvent('loadstart')
249
       this._uploadStarted = true
249
       this._uploadStarted = true
265
   }
265
   }
266
 
266
 
267
   _onError(err) {
267
   _onError(err) {
268
+    let statusCode = Math.floor(this.status)
269
+    if(statusCode >= 100 && statusCode !== 408) {
270
+      return
271
+    }
268
     log.verbose('XMLHttpRequest error', err)
272
     log.verbose('XMLHttpRequest error', err)
269
     this._statusText = err
273
     this._statusText = err
270
     this._status = String(err).match(/\d+/)
274
     this._status = String(err).match(/\d+/)
271
     this._status = this._status ? Math.floor(this.status) : 404
275
     this._status = this._status ? Math.floor(this.status) : 404
272
     this._dispatchReadStateChange(XMLHttpRequest.DONE)
276
     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) {
274
       this.dispatchEvent('timeout')
278
       this.dispatchEvent('timeout')
275
     }
279
     }
276
     this.dispatchEvent('loadend')
280
     this.dispatchEvent('loadend')