fetch().then() return content-type and body(fetch().then() 返回内容类型和正文)
问题描述
互联网上的每个 fetch API 示例都展示了如何使用 response.json()、response.blob() 等仅返回正文.我需要的是调用一个同时具有内容类型和主体作为 blob 的函数,但我不知道该怎么做.
Every fetch API example on the internet shows how to return only the body using response.json(), response.blob() etc. What I need is to call a function with both the content-type and the body as a blob and I cannot figure out how to do it.
fetch("url to an image of unknown type")
.then((response) => {
return {
contentType: response.headers.get("Content-Type"),
raw: response.blob()
})
.then((data) => {
imageHandler(data.contentType, data.raw);
});
这显然不起作用:data.contentType 已填充,但 data.raw 是一个承诺.如何在同一上下文中获取这两个值?
This obviously doesn't work: data.contentType is filled, but data.raw is a promise. How can I get both values in the same context?
推荐答案
你可以这样写:
fetch("url to an image of unknown type")
.then(response => {
return response.blob().then(blob => {
return {
contentType: response.headers.get("Content-Type"),
raw: blob
}
})
})
.then(data => {
imageHandler(data.contentType, data.raw);
});
或者这样
fetch("url to an image of unknown type")
.then(response => {
return response.blob().then(blob => {
imageHandler(response.headers.get("Content-Type"), blob)
})
})
在这两种情况下,您都将收到已解析的 blob
的回调保留在您有权访问 response
的范围内.
In both cases you keep the callback in which you receive the resolved blob
within the scope where you have access to response
.
这篇关于fetch().then() 返回内容类型和正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:fetch().then() 返回内容类型和正文


基础教程推荐
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01