如何知道Fetch API中的响应类型?
在XMLHttpRequest中,有responseType
property表示返回的响应主体的类型(json,text,blob等)。在Fetch API response中,即使有解析其正文的有用方法(didReceiveApplicationContext
,json()
,text()
等),我仍然没有找到任何属性与XMLHttpRequest的blob()
属性一样,用于指示响应的类型。
答案 0 :(得分:2)
我认为您可以检查内容类型的响应标头,如下所示:
response.headers.get("content-type")
答案 1 :(得分:0)
我认为 orangespark 是对的。应使用 content-type
响应标头。
如果 content-type
标头丢失或无效。可以进一步处理响应:
当提取一个 MIME 类型返回失败或一个 MIME 类型对于给定格式本质不正确时,将其视为致命错误。现有的网络平台功能并非总是遵循这种模式,多年来,这一直是这些功能中安全漏洞的主要来源。相比之下,通常可以安全地忽略 MIME 类型的参数。 https://fetch.spec.whatwg.org/#content-type-header
由于有许多有效的媒体类型,一些库懒惰探测 Content-Type
标头:response.headers.get("content-type").includes('json')
为 json
存在,在 {{1 }} 被调用。
在 Media types 中注册了 1500 多个 IANA,可以将其设置为请求的 Content-Type。
如果 response.json()
未设置(或忘记设置)。服务器可能设置了 content-type
的 default,这会“中断”您的响应处理。
如果 text/plain
不是可接受的媒体类型之一,或者 content-type
与 body
不匹配 ...
请求:
<块引用>接受:文本/html、图像/avif;q=0.9、图像/apng;q=0.8
响应(差):
<块引用>内容类型:应用程序/json
...在阅读 content-type
之前,您可以使您的应用程序更加安全并clone()
response
。所以你仍然可以返回 JSON,例如无法解析为 JSON 的 body
响应错误。
text
您可以使用 response.blob()
作为 const response2 = response.clone();
let data;
try {
data = await response.json(); // SyntaxError: Unexpected token in JSON
} catch (e) {
text = await response2.text(); // response clone can still read as a fallback
data = {
error: e.message,
invalidJson: text
};
}
、response.text()
、...的替代方案
返回的 response.json()
具有保存 Blob
标头值的属性 blob.type
。
以下是一些示例,说明如何处理这些 blob:
content-type
内容image/svg+xml
内容text/html
内容application/json
内容application/octet-stream
内容???/???