繁体   English   中英

如何在 React Native 中知道 API 响应的 Content-Type

[英]How to know the Content-Type of the API response in 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但它检查响应代码而不是内容类型。

知道response Content-Type的正确方法是什么?

更新(答案):

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

 }else{
         
    //Response is in text/html

 }

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

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

因为 fetch 会给你带有 headers 对象的响应。 您可以简单地从 headers 对象中获取它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM