When I tried to post data from react-native to PHP API, react-native show the error:
Json Parse error: Unrecognized token '<'
I tested PHP API by postman with the header type 'application/json', it works fine, here is the react-native code, can anyone help me on this? Thanks in advance!
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
ActivityIndicatorIOS,
TextInput,
TouchableOpacity,
} from 'react-native';
const REQUEST_URL = 'http://localhost:8000/user';
export default class extends Component {
constructor(props) {
super(props);
}
_submit() {
fetch(REQUEST_URL, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstname: "Justin", lastname: "Robot"
})
})
.then((response) => response.json())
.then((responseData) => {
console.log(responseData.body);
})
.done();
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity
style={styles.submitButton}
onPress={() => this._submit()}
>
<Text>http post</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
submitButton: {
backgroundColor: 'lightskyblue',
borderRadius: 5,
paddingTop: 5,
paddingBottom: 5,
paddingLeft: 20,
paddingRight: 20,
}
});
The Fingerprint error "Unrecognized Token" indicates that a one of the printer commands within the print job sent to (or program running on) the printer has been correctly used: except that the command was given an invalid argument.
TL;DR: In React Native, you will get “SyntaxError: JSON Parse error: Unrecognized token '<'” if your URL returns a 404 error, or in general if the content is not a JSON string. In a recent post, I showed how to display a list of movies that had been fetch ed from a REST API.
Re: Unexpected token in JSON at position 0 This usually means that an error has been returned and that's not valid JSON. Check the browser developer tools console and network tabs. Turn on Debugging and (after reproducing the error) check the web server error logs.
We just ran into this in React Native because our server was returning an error response via HTML.
<html>
<head><title>413 Request Entity Too Large</title></head>
<body bgcolor="white">
<center><h1>413 Request Entity Too Large</h1></center>
<hr><center>nginx</center>
</body>
</html>
The fixes could be any of the following:
1) Prevent the error from happening in your server side code.
2) Do better error handling on your server to return JSON errors instead of HTML errors.
3) Write some client side code to detect that HTML was returned and show a more useful error message.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With