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

前端 未结 10 1591
执笔经年
执笔经年 2020-12-09 11:21

\"JSON Parse error: Unrecognized token\'<\'\" Error is showing while hitting the api. Code is attached below Note* : Response is in the JSON format.

相关标签:
10条回答
  • 2020-12-09 12:04

    I also encountered this problem before. I solved it by adding this as a parameter in fetch.

    header: {
      'Content-Type': 'application/json'
    }
    

    If it doesn't work, it's more likely an internal server error in the web service. Cheers.

    0 讨论(0)
  • 2020-12-09 12:06

    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")
    };

    0 讨论(0)
  • 2020-12-09 12:06

    I fixed this problem my changing the multiline URLs in template literals to single-line URLs.

    I had this problem on iOS, but not Android. The "same" code according to version control, and state according to testing procedures, led to this error on the iOS device emulator but not the Android device emulator.

    Apple and Windows use different line endings, which is important considering template literals allow multiline strings.

    // failed in iOS
    fetch(`https://<API-NAME>/
    ?param1=${param1}
    &param2=${param2}`);
    
    // consistently works
    fetch(`https://<API-NAME>/?param1=${param1}&param2=${param2}`);
    
    0 讨论(0)
  • 2020-12-09 12:09

    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.

    0 讨论(0)
提交回复
热议问题