React native http post得到了Json Parse错误:无法识别的标记'<'

Jus*_*tin 5 php rest json ios react-native

当我尝试将数据从react-native发布到PHP API时,react-native显示错误:

Json Parse错误:无法识别的标记'<'

我通过邮递员使用标题类型'application/json'测试了PHP API,它运行正常,这里是反应原生代码,任何人都可以帮助我吗?提前致谢!

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,
  }
});
Run Code Online (Sandbox Code Playgroud)

Pau*_*est 4

我们刚刚在 React Native 中遇到了这个问题,因为我们的服务器通过 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>
Run Code Online (Sandbox Code Playgroud)

修复可能是以下任意一种:

1)防止服务器端代码中发生错误。

2) 在服务器上进行更好的错误处理,返回 JSON 错误而不是 HTML 错误。

3) 编写一些客户端代码来检测 HTML 是否已返回并显示更有用的错误消息。