【发布时间】:2022-06-13 22:37:58
【问题描述】:
我正在调用后端微服务的 API 端点,该微服务下载 HTML 文件作为 API 数据响应。我正在使用 ReactJS 和 Axios 库来调用后端微服务,并且得到了很好的响应。
在我的代码的 .then 块中,我使用 JavaScript Blob 来处理响应数据并将其保存为 HTML 文件。这段代码基本上从 API 调用中获取响应,并将数据准备为具有自定义文件名的可下载链接。
当块的link.click() 部分被执行时,下载会自动开始。
但是,我遇到的问题是响应是让我的网络浏览器下载相同的 HTML 文件两次。
我正在尝试弄清楚如何只下载一次而不是多次下载文件。
这是我的代码:
const callAPI = () => {
Axios.post(api_endpoint, bodyArgs)
.then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", `${company}_${startDate}_${endDate}.html`);
document.body.appendChild(link);
link.click();
})
.catch(function (error) {
console.log(error);
alert(
"Sorry, there was an error processing your request. Please check the dates of your report and try again!"
);
});
};
我的代码的.then 块中是否存在问题,或者这是特定于网络浏览器的问题?任何帮助是极大的赞赏。谢谢。
【问题讨论】:
标签: javascript