5
votes

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,
  }
});
1
change: .then((response) => response.json()) as .then((response) => console.log(response)) , what do you see in console?Ivan Chernykh
My guess would be that you are getting XML returned from your server and trying to parse it as JSON. Just a guess.Putz1103
hi, I got console.log(response) as: [info][tid:com.facebook.react.JavaScript] { type: 'default', status: 500, ok: false, statusText: undefined, headers: { map: { 'content-type': [ 'text/html; charset=UTF-8' ], 'x-powered-by': [ 'PHP/5.5.34' ], date: [ 'Mon, 13 Jun 2016 20:31:03 GMT' ], host: [ 'localhost:8000' ], 'cache-control': [ 'no-cache, private' ], connection: [ 'close' ] } }, url: 'localhost:8000/user', _bodyInit: '<!DOCTYPE html>\n<html>\n ...... seems the problem is on API.Justin

1 Answers

4
votes

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.