gpt4 book ai didi

javascript - 为类型为 'document' 的请求获取元数据时发送自定义 header

转载 作者:行者123 更新时间:2023-12-05 05:32:41 33 4
gpt4 key购买 nike

问题

我需要使用 javascript 和获取 api 进行经过身份验证的下载。但是,会自动调用 document 类型的后端(即 request to fetch metadata ),它不会从自定义 header (XCompanyAccessToken) 中获取必要的访问 token 实际创建要下载的文件。


代码

我目前正在使用我在网上找到的以下代码:

function download(fileUrl) {
let fileName;
fetch(fileUrl, , {
method: 'GET',
headers: {
'XCompanyAccesstoken' = '<access-token>',
/* more headers, obsolete here */
},
mode: 'cors',
})
// the whole then blocks here only handle gziped files, but I left it here for completeness
.then(response => {
const contentEncodingHeader = response.headers?.get('Content-Encoding');
if (contentEncodingHeader === 'gzip') {
// kudos: https://stackoverflow.com/questions/40939380/how-to-get-file-name-from-content-disposition
// there is no "build-in" way of parsing this, unfortunately.
const contenDispositionHeader = response.headers?.get('Content-Disposition');
const fileNameSplit = contenDispositionHeader?.split('filename=')?.[1];
// removes double quotes at the beginning and end
fileName = JSON.parse(fileNameSplit ?? '""');
return response.blob();
}
return null;
})
.then(blobby => {
if (blobby) {
const objectUrl = window.URL.createObjectURL(blobby);

anchor.href = objectUrl;
anchor.download = fileName;
anchor.click();

window.URL.revokeObjectURL(objectUrl);
}
})
}

并且这些 header 在对 fetch 类型后端的调用中正确设置,但在对 document 类型后端的调用中丢失。

为了使下载工作,响应 header 公开了以下 header :

access-control-expose-headers:内容配置、内容编码

并且值设置正确:

content-disposition: attachment; filename="2022-10-12_13-12_download.csv"
content-type: text/csv; charset=UTF-8

(注意:未设置内容编码 header )

但是,如前所述,完成了对后端的三个调用。

  1. 预检(运行良好)
  2. 元数据调用(需要 token ,但没有得到)
  3. 获取(具有 token ):


我试过了

用谷歌搜索了十几种不同的方法,所有方法都在询问如何为下载的元数据添加自定义 header ?,但找不到任何相关信息。

除此之外,我注意到,在获取元数据时 cookie 会发送到后端:

所以我尝试将访问 token 添加到 cookies programmatically ,但 cookie 被忽略,因为 cookie header 不包含以编程方式设置的 cookie。


最后是问题

有什么办法可以让我完成这项工作吗?

有什么方法可以在浏览器决定启动类型为 document 的调用以检索元数据时将自定义 XCompanyAccessToken header 发送到后端?

后端是否需要为此进行任何更改?

最佳答案

document 请求是由浏览器发起的请求(例如,通过页面导航,用户在地址栏中输入 URL,或者在您的情况下,通过 打开链接anchor.click();).

不能为这些请求设置自定义 header ,因为它们的生命周期在浏览器而非客户端 javascript 代码的控制之下。

但可以做的是从 javascript 设置适当的 cookie,它们将在发出请求时发送。如果你在javascript中设置的cookie没有按预期发送,检查是否是跨域请求。还要检查 cookie 上的 SameSite 策略,以确保允许浏览器发送 cookie。

https://medium.com/swlh/7-keys-to-the-mystery-of-a-missing-cookie-fdf22b012f09是一篇帮助您调试丢失的 cookie 的好文章。

关于javascript - 为类型为 'document' 的请求获取元数据时发送自定义 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74042116/

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