I am currently working with a fetch() request that can either return a zip file (blob) or a JSON object in case of an error. The existing code successfully handles the zip file by sending it to the user's Downloads folder. However, when a JSON response is returned, it unintentionally creates an empty or corrupt zip file.
Is there a way to conditionally process the Response object to prevent downloading a file if it's a JSON? Additionally, I want to save the Response.json() into a variable. How should I modify the code to achieve this?
await fetch(params)
.then(res => res.blob())
.then(blob => {
let url = window.URL.createObjectURL(blob);
let a = document.createElement('a');
a.href = url;
a.download = name + ".zip";
document.body.appendChild(a);
a.click();
a.remove(); //afterwards we remove the element
}).catch(err => console.error(err));