0

I tried to do a fetch on a URL that is working when I use on postman, but when I try to do the same on react native (after doing the same procedure on different URLs) I got an error saying JSON Parse error: Unregonized token '<' that seems to be because the programs fails to convert the HTML response into JSON using the .json(). Here's the code I'm currently running:

    GetMonthData = async () => {
 let UserID = await AsyncStorage.getItem('userID');
 this.setState({ UserID: UserID })

return fetch('https://guardianes.centeias.net/user/calendar/month', {
    method: 'GET',
    headers: {
        user_id: this.state.UserID,
    }})
.then((response) => response.json())
.then((responseJson) => {

  this.setState({
    isLoading: false,
    dataSource: responseJson.data,
  }, function(){

  });

})
.catch((error) =>{
  console.error(error);
});

Here's the error I get while running the app on device

The problem is that I searched a lot already and can't seem to find a solution. Thanks for any help.

  • Possible duplicate of ["SyntaxError: Unexpected token < in JSON at position 0" in React App](https://stackoverflow.com/questions/37280274/syntaxerror-unexpected-token-in-json-at-position-0-in-react-app) – JJJ Sep 05 '18 at 20:26
  • mine is different from this one, because that one doesnt have a fetch – Vinicius Porto Sep 05 '18 at 20:33
  • ...why would that make any difference? You're getting HTML back. It's the exact same issue. – JJJ Sep 05 '18 at 20:42

1 Answers1

0

It's very possible that the request is failing for fetch, hence why it returns an HTML code that most likely contains the HTML code for a 404 page instead of a parseable JSON data.

When using fetch, make sure to check if the response status is of OK type.

fetch("http://httpstat.us/500")
.then(function(response) {
    if (!response.ok) {
        throw Error(response.statusText);
    }
    return response;
}).then(function(response) {
    console.log("ok");
}).catch(function(error) {
    console.log(error);
});

More info here: https://www.tjvantoll.com/2015/09/13/fetch-and-errors/


Remember, when fetch gets a non-ok status code, it doesn't go straight to the .catch(). It goes to the .then() function; one of the main criticisms of fetch.