问题
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