如何检查fetch的响应是否是javascript中的json对象

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();
});
Run Code Online (Sandbox Code Playgroud)

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
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

如果您需要绝对确定内容是有效的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
    }
  });
Run Code Online (Sandbox Code Playgroud)

异步/ 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
  }
}
Run Code Online (Sandbox Code Playgroud)

  • @WouterRonteltap:您不是只允许做一个或另一个。好像我记得您在response.anything()上一针见血。如果是这样,则JSON是文本,但文本不一定是JSON。因此,您必须首先确定是.text()。如果您首先执行.json(),但失败了,我认为您没有机会也执行.text()。如果我错了,请向我展示不同的内容。 (3认同)
  • 在我看来,您不能信任标头(即使您应该信任,但有时您只是无法控制另一端的服务器)。所以很高兴您还在答案中提到了 try-catch。 (3认同)
  • @Andy您可以调用response.clone()来获取克隆实例,因此您可以多次调用.json()或.text()。参考:https://developer.mozilla.org/en-US/docs/Web/API/Response/clone (3认同)
  • 正如https://stevenklambert.com/writing/fetch-json-text-fallback/文章也提到的那样,使用clone(),你可以: fetch('/file') .then(response => response.clone ().json().catch(() => response.text()) ).then(data => { // 数据现在解析为 JSON 或原始文本 }); (3认同)
  • 是的,@Lonnie Best 在这一点上是完全正确的。如果你调用 .json() 并且它抛出异常(因为响应不是 json),如果你随后调用 .text(),你将得到一个“Body has already beused”异常 (2认同)

lar*_*rbo 6

您可以使用辅助函数干净利落地做到这一点:

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)
  }
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

fetch(URL, options)
.then(parseJson)
.then(result => {
    console.log("My json: ", result)
})
Run Code Online (Sandbox Code Playgroud)

这将引发错误,因此您可以catch根据需要进行操作。