I am new to react native and I am calling GET API using fetch in react-native but sometimes the response Content-Type is text/html and sometimes response Content-Type is application/json.
I want to check the response Content-Type first before I do response.json().
I tried using try-catch but it displays a warning on the android screen when try case fail.
try{
return response.json();
}catch(e){
}
I also tried response.ok but it checks for response code instead of a content type.
What's the correct way to know the response Content-Type?
UPDATE(Answer):
if(response.headers.get("Content-Type").indexOf("application/json")>=0){
//Response is in JSON
}else{
//Response is in text/html
}
You can use .get(param) on response headers.
response.headers.get("Content-Type")
As fetch will give you response with headers object. You can simply get it from headers object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With