Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know the Content-Type of the API response in react native

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

 }
like image 406
Archit Sandesara Avatar asked Nov 15 '25 12:11

Archit Sandesara


1 Answers

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.

like image 156
Jai Avatar answered Nov 18 '25 21:11

Jai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!