php - React native http post 得到 Json Parse 错误 : Unrecognized token '<'

标签 php ios json rest react-native

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

Json Parse error: Unrecognized token '<'

我通过 postman 使用 header 类型“application/json”测试了 PHP API,它工作正常,这是 react-native 代码,有人可以帮助我吗?提前致谢!

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

最佳答案

我们刚刚在 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>

修复可以是以下任何一种:

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

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

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

关于php - React native http post 得到 Json Parse 错误 : Unrecognized token '<' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37797822/

相关文章:

javascript - 我应该使用哪种方法来禁用按钮

ios - UITableView 顶部和底部单元格在加载和每次更新时扩展

ios - 应用程序:didRegisterForRemoteNotificationsWithDeviceToken: not called ios 10. 3.2

json - Jersey 在 Spring 中实现 ContextResolver<JAXBContext>

php - 带有 php 函数的图像链接

javascript - 在不刷新页面的情况下插入记录后显示 <select> 选项

php - MySQL在一个唯一名称下设置多个版本的数据

ios - 选择时 uitableviewcell 损坏(从底部看到)

java - Spring MVC - 将 JSON 对象从 Ajax post 请求映射到 Java 对象

javascript - 下划线 JSON 中的 js groupby 数组