【发布时间】:2021-02-21 01:06:09
【问题描述】:
我是 react native 的新手,我在 react-native 中使用 fetch 调用 GET API,但有时响应 Content-Type 是 text/html,有时响应 Content-Type 是 application/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