Skip to content

Commit

Permalink
Add responseType check and try-catch block to process response safely.
Browse files Browse the repository at this point in the history
  • Loading branch information
enginustun committed Dec 10, 2018
1 parent f7c123c commit 4dbb76c
Showing 1 changed file with 14 additions and 10 deletions.
24 changes: 14 additions & 10 deletions dev/modules/xhr.js
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down

0 comments on commit 4dbb76c

Please sign in to comment.