From 4dbb76c842d1b644caae9276a6be85ea29703389 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?engin=20=C3=BCst=C3=BCn?= Date: Mon, 10 Dec 2018 16:01:32 +0300 Subject: [PATCH] Add responseType check and try-catch block to process response safely. --- dev/modules/xhr.js | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/dev/modules/xhr.js b/dev/modules/xhr.js index 2c74129..ac5547f 100644 --- a/dev/modules/xhr.js +++ b/dev/modules/xhr.js @@ -30,17 +30,21 @@ class XHR { settings.afterEveryRequest(this.xhr); afterRequest(this.xhr); if (this.xhr.status >= 200 && this.xhr.status < 300) { - let data = this.xhr.responseText; - const contentType = ( - this.xhr.getResponseHeader('Content-Type') || '' - ).toLowerCase(); - if ( - this.xhr.responseText && - contentType.includes('application/json') - ) { - data = JSON.parse(this.xhr.responseText); + try { + const responseType = this.xhr.responseType.toLowerCase(); + let data = this.xhr.response; + if (['', 'text'].includes(responseType)) { + const contentType = ( + this.xhr.getResponseHeader('Content-Type') || '' + ).toLowerCase(); + if (data && contentType.includes('application/json')) { + data = JSON.parse(this.xhr.responseText); + } + } + resolve(data); + } catch (error) { + reject(error); } - resolve(data); } else { try { reject(JSON.parse(this.xhr.responseText || this.xhr.statusText));