Reputation: 655
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
}
Upvotes: 4
Views: 4950
Reputation: 74738
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.
Upvotes: 4