简体   繁体   English

JavaScript:有条件地处理获取响应

[英]JavaScript: Conditionally process fetch response

I have a fetch() request returning a Response object that is either a zip file (blob) or a JSON if there was an error with the request.我有一个 fetch() 请求返回响应 object,如果请求有错误,它是 zip 文件(blob)或 JSON。 The code I have successfully processes the zip file and sends it to the users Downloads folder.我已成功处理 zip 文件并将其发送到用户下载文件夹的代码。 When a JSON response is returned, the code creates a empty/corrupt zip file.当返回 JSON 响应时,代码会创建一个空的/损坏的 zip 文件。

How would I go about conditionally processing the Response object so that it prevents a file from being downloaded if it is a JSON?我 go 如何有条件地处理响应 object,以防止文件被下载(如果它是 JSON)? I would also like to store Response.json() in a variable?我还想将 Response.json() 存储在变量中?

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));

Thanks for the suggestions all.感谢大家的建议。 Per @Barmer and @Bergi suggestions I was able to redefine the API so that my error content is now just inside of a header. The solution I found looks like this:根据@Barmer 和@Bergi 的建议,我能够重新定义 API,这样我的错误内容现在就在 header 的内部。我找到的解决方案如下所示:

await fetch(params)
.then(function(response) {
   if (response.headers.get('X-Error') == 'False') {
      return response.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();
         }).catch(err => console.error(err))
   }
   //process error from backend
   console.log(response.headers.get('X-Error'))
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM