Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Native Fetch "POST" request throwing "SyntaxError: Unexpected end of JSON input" in Android

this is my function
don't know where is the problem

fetchData() {
        fetch(REQUEST_URL, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        Request : 'menu',
        active : '1',
      })
    }).then((response) => response.json())
    .then((responseData) => {
        this.setState({
              menu: responseData.Response,
          }); 
    })
    .catch((error) => {
      console.warn('error',error);
    })
    .done();
      }

please point out the problem in function

like image 838
Hafiz Awais Saleem Avatar asked Feb 07 '23 01:02

Hafiz Awais Saleem


1 Answers

The error occcurs because your response cannot be casted to JSON format. This issue might happen because of wrong header, response body, or other various reasons based on your server. The way to go - since apparently the responses are not consistent - is to perform additional validation of server response before trying to cast the response to JSON.

You can do this by replacing:

.then((response) => response.json())

with

.then((response) => {
  // In this case, we check the content-type of the response
  if (response.headers.get('content-type').match(/application\/json/)) {
    return response.json();
  }
  return response;
  // You can also try "return response.text();"
 })
like image 197
Gabriel Lupu Avatar answered Feb 09 '23 14:02

Gabriel Lupu