使用php json和react-native获取数据时出现问题

时间:2019-06-20 14:19:34

标签: php mysql json react-native

我目前正在使用react-native开发一个简单的登录功能,该功能使用php和json从mysql获取数据。 我面临的问题是,我一遍又一遍地遇到“ JSON解析错误:意外的EOF”,我不知道该怎么办。

我相信问题必须出在react-native组件中,因为我已经在Postman上测试了PHP文件,并且得到了我要的东西。

由于某种原因,该帖子被确定为与sql-inyections有关的问题的可能重复,而这并不是我要的。

这是我编写的代码:

本机:

  constructor(props) {
    super(props);
    this.state = { 
      userCI:'',
      userPassword:''

    };
  }


  login = () => {
    // Get data from PHP endpoint
    const {userCI} = this.state;
    const {userPassword} = this.state;

    fetch('http://192.168.1.14/dashboard/endpoint.php', {
      method:'POST',
      headers: {
          'Accept': 'application/json; text/plain; */*',
          'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        ci: userCI,
        password: userPassword,
        key:'test',
      })

    })
    .then(response => response.json())
    .then(response => {
      alert(response.message);
    })
    .catch(error =>{
      console.error(error);
    })
    .done();
  }

  render() {
    return (
      <View>
        <TextInput
          style={styles.Input}
          placeholder={'Usuario'}
          onChangeText= {
            userCI => this.setState({userCI})
          }
        />
        <TextInput 
          style={styles.Input}
          secureTextEntry={true} 
          placeholder={ 'Contraseña'} 
          onChangeText= {
            userPassword => this.setState({userPassword})
          }
        />
        <Button 
          style={styles.button} 
          onPress={this.login} 
          title={'Conectarse'} 
        />
      </View>

    );

  }
}

PHP:


    class User {
        private $db;
        private $connection;
        function __construct() {
            $this->db = new DB_Connection();
            $this->connection = $this->db->get_connection();
        }
        public function does_user_exist($ci, $password){
            $query = "SELECT * FROM users WHERE ci='$ci' AND password='$password'";
            $result = mysqli_query($this->connection, $query);
            if(mysqli_num_rows($result) > 0){
               $json['success'] = 'Bienvenido';
               echo json_encode($json);
               mysqli_close($this->connection);
            }else{
                $json['error'] = 'Wrong password';
                echo json_encode($json);
                mysqli_close($this->connection);
            }
        }
    }

    $user = new User();
    if(isset($_POST['ci'],$_POST['password'])) {
        $ci = $_POST['ci'];
        $password = $_POST['password'];
        if (!empty($ci) && !empty($password)) {
            $encrypted_password = md5($password);
            $user->does_user_exist($ci, $password);
        } else {
            echo json_encode(array(
                'message' => 'There was a unexpected error',
            ));
        }
    }

请,如果有人可以帮助我,我将非常高兴。 谢谢!

0 个答案:

没有答案