如何知道本机反应中 API 响应的内容类型

How to know the Content-Type of the API response in react native

我是 React Native 的新手,我在 react-native 中使用 fetch 调用 GET API 但有时响应 Content-Typetext/html 有时响应 Content-Typeapplication/json。 我想在执行 response.json() 之前先检查响应 Content-Type。 我尝试使用 try-catch,但当 try case 失败时它会在 android 屏幕上显示警告。

try{
return response.json();
}catch(e){

}

我也试过 response.ok 但它检查的是响应代码而不是内容类型。

responseContent-Type的正确认识方法是什么?

更新(答案):

if(response.headers.get("Content-Type").indexOf("application/json")>=0){
  
    //Response is in JSON

 }else{
         
    //Response is in text/html

 }

您可以在响应 headers 上使用 .get(param)

response.headers.get("Content-Type")

因为 fetch 会给你 headers object 的回应。您可以简单地从 headers object.

获取它