JSON Parse error: Unrecognized token'<' - react-native

You can try by adding the headers to your fetch api, as it posts your record to your url.

var dataObj = {}
dataObj.uname = uname,
dataObj.password = password

fetch("http:/example.com", {
  method: 'post',
  headers: {
    'Accept': 'application/json, text/plain, */*',  // It can be used to overcome cors errors
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(dataObj)
})
.then((response) => response.json())
.then((responseData) => {
  AlertIOS.alert(
      "POST Response",
      "Response Body -> " + JSON.stringify(responseData.body)
  )
}).done();
    this.props.navigation.navigate("Home")
};

This Means you are getting Html response from the server probably a 404 or 500 error. Instead of response.json() use response.text() you will get the html in text.

fetch("http:/example.com", {method: "POST",
  body: JSON.stringify(
    {
      uname: uname,
      password: password      
    }
  )
})
.then((response) => response.text())
.then((responseData) => {
  AlertIOS.alert(
      "POST Response",
      "Response Body -> " + responseData
  )
}).done();
       this.props.navigation.navigate("Home")
   };

I am pretty sure all these answers are correct. From what I have seen, if you have properly set the request header with:

headers:{
    'Accept': 'application/json',
    'Content-Type':'application/json'
}

The Accept header will tell the server what data type we are sending. Content-Type tells the client of what the response data type will be.

You most likely had to change the format of the body because the server may not be setup to handle application/json data types. In this case if you have access to your server you can add it to a config file or in .htaccess. If you still get the error, then there is an error in the server's json response.

If you haven't used POSTMAN for API testing, go and grab it because it has helped me lots with debugging API's.


Finally The below code worked. The problem was with Body parameters.

fetch("http:/example.com", {method: "POST",
  body: "uname=value1&password=value2" // <-- Post parameters        
})
.then((responseData) => {
  AlertIOS.alert(
      "POST Response",
      "Response Body -> " + JSON.stringify(responseData.body)
  )
}).done();
       this.props.navigation.navigate("Home")
};

Tags:

React Native