我正在使用 fetch polyfill 从 URL 中检索 JSON 或文本,我想知道如何检查响应是 JSON 对象还是只是文本
fetch(URL, options).then(response => {
// how to check if response has a body of type json?
if (response.isJson()) return response.json();
});
原文由 Sibelius Seraphini 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以检查响应的
content-type
,如 MDN 示例 所示:如果您需要绝对确定内容是有效的 JSON(并且不信任标头),您总是可以接受响应
text
并自己解析:异步/等待
如果您使用的是
async/await
,您可以以更线性的方式编写它: