gpt4 book ai didi

javascript - 在 javascript 中使用 fetch 时访问 header

转载 作者:行者123 更新时间:2023-12-04 01:07:01 28 4
gpt4 key购买 nike

我正在使用以下命令从我的 nodejs 服务器向浏览器发送一个 zip 文件

res.set("Content-Type", "application/octet-stream");
res.set("Content-disposition", `attachment; filename="`+zip_name+`.zip"`);
res.set("Content-Length", zipBuff.length);
res.send(zipBuff);

然后我使用 :

获取它
fetch("/my/url", {
method: "POST",
body: formData,
})
.then(response => {
return response.blob();
})
.then(response => {
const blob = new Blob([response], {type: 'application/zip'});
const downloadUrl = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = downloadUrl;
a.download = "blah.zip";
document.body.appendChild(a);
a.click();
});

我希望能够使用 zip_name 而不是 blah 作为文件名,但我不知道如何访问 header (在那种情况下 Content-disposition) 响应的 fetch

有人可以解释一下这是怎么做到的吗?

最佳答案

返回对象中的 blob 和 header

fetch("/my/url", {
method: "POST",
body: formData,
})
.then(response => {
const headers = response.headers
return { blob: response.blob(), headers }
})
.then(({blob, headers}) => {
/// now you can access to **headers** and blob data
});

更新:

要访问 header ,请使用 headers.get("Header name").split('=').pop()

UPD1:

const foo = async () => {
const response = await fetch("/my/url", {
method: "POST",
body: formData,
})
if(!response.ok)
thorw new Error("Some error happend")

const blod_data = await response.blob()
const header_with_name = response.headers.get("Header name").split('=').pop()
// do something with it
}

关于javascript - 在 javascript 中使用 fetch 时访问 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66104023/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com