【问题标题】:How to know the Content-Type of the API response in react nativereact native如何知道API响应的Content-Type
【发布时间】:2021-02-21 01:06:09
【问题描述】:

我是 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

 }

【问题讨论】:

  • 它给出了undefined。但是,当我在字符串中执行JSON.stringify(response.headers) 时,会出现"content-type":"application/json"
  • 发了一个答案,看看吧。

标签: javascript reactjs react-native react-native-android


【解决方案1】:

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

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

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

【讨论】:

  • 它提供了应用程序/json; charset=utf-8.
  • 然后我像这样检查了。 response.headers.get("Content-Type").indexOf("application/json")>=0
  • 很高兴这对您有所帮助。
  • @ArchitSandesara,您能否在您的问题中发布成功为您工作的代码?
猜你喜欢
  • 2011-02-03
  • 2013-08-13
  • 2020-10-05
  • 1970-01-01
  • 1970-01-01
  • 2017-01-24
  • 2023-04-07
  • 1970-01-01
  • 2022-06-30
相关资源
最近更新 更多