Sib*_*ini 74 javascript json fetch-api
我正在使用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();
});
nil*_*ils 117
您可以检查content-type响应的响应,如此MDN示例所示:
fetch(myRequest).then(response => {
  const contentType = response.headers.get("content-type");
  if (contentType && contentType.indexOf("application/json") !== -1) {
    return response.json().then(data => {
      // process your JSON data further
    });
  } else {
    return response.text().then(text => {
      // this is text, do something with it
    });
  }
});
如果您需要绝对确定内容是有效的JSON(并且不信任标题),您可以随时接受响应text并自行解析:
fetch(myRequest)
  .then(response => response.text())
  .then(text => {
    try {
        const data = JSON.parse(text);
        // Do your JSON handling here
    } catch(err) {
       // It is text, do you text handling here
    }
  });
异步/ AWAIT
如果您正在使用async/await,您可以以更线性的方式编写它:
async function myFetch(myRequest) {
  try {
    const reponse = await fetch(myRequest); // Fetch the resource
    const text = await response.text(); // Parse it as text
    const data = JSON.parse(text); // Try to parse it as json
    // Do your JSON handling here
  } catch(err) {
    // This probably means your response is text, do you text handling here
  }
}
您可以使用辅助函数干净利落地做到这一点:
const parseJson = async response => {
  const text = await response.text()
  try{
    const json = JSON.parse(text)
    return json
  } catch(err) {
    throw new Error("Did not receive JSON, instead received: " + text)
  }
}
然后像这样使用它:
fetch(URL, options)
.then(parseJson)
.then(result => {
    console.log("My json: ", result)
})
这将引发错误,因此您可以catch根据需要进行操作。
| 归档时间: | 
 | 
| 查看次数: | 39375 次 | 
| 最近记录: |