How do download of Json using Fetch in JavaScript?

梦想的初衷 提交于 2019-12-13 08:58:30

问题


how do download of a JSON required from Fetch URL?

Download is in XLSX.

CODE

function teste (){

alert(fetch ("url")        
.then(response => response.json())
.then(data => { console.log(data)})
     .then(response => response.blob())
        .then(blob => {
            var url = window.URL.createObjectURL(blob);
            var a = document.createElement('a');
            a.href = url;
            a.download = "filename.xlsx";
            a.click();                    
        })
)
}

回答1:


Remove alert(), return value from .then(). Note Response can only be read once

function teste() {   
  fetch("url")
    .then(async(response) => {
      let clone = response.clone();
      let res = await clone.json();
      console.log(res);
      return response.blob()
    })
    .then(blob => {
      var url = window.URL.createObjectURL(blob);
      var a = document.createElement('a');
      a.href = url;
      a.download = "filename.xlsx";
      a.click();
    })
    .catch(function(err) {
      console.error(err)
    })
}


来源:https://stackoverflow.com/questions/46797810/how-do-download-of-json-using-fetch-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!