How to fetch in JavaScript URLs which respond GZIP headers

Viewed 688

I am looking how to fetch in JavaScript URLs which respond GZIP headers then parse the content to JSON. I have tried :

function fetchJson(url, callback = null, callbackError = null, unzip = false) {
    fetch(url) 
    .then(r => { 
        if (unzip) r = atob(r);
        return r.json();
    })  
    .then(r => {
        if (callback !== null) callback(r);
    })  
    .catch(err => {
        console.error(err);
        if (callbackError !== null) callbackError();
    }); 
};  

But I get this error :

DOMException: String contains an invalid character
1 Answers

There's no need to manually decompress responses, and atob would not be the way to do it. If your unzip parameter was truthy, that likely would've caused the error. Also if this function should only ever fetch JSON, it might be handy to set that explicitly as a header.

function fetchJson(url, callback = null, callbackError = null) {
  fetch(url, { headers: { 'accept': 'application/json; charset=utf8;' } }) 
    .then(r => return r.json())  
    .then(r => {
      if (callback !== null) callback(r);
    })  
    .catch(err => {
      console.error(err);
      if (callbackError !== null) callbackError();
    }); 
};  
Related