Логин React Native MySQL - PullRequest
       21

Логин React Native MySQL

1 голос
/ 21 апреля 2020

У нас возникла проблема с нашим кодом для входа. Мы продолжаем получать SyntaxError: JSON Ошибка разбора:

enter image description here

Мы сузили ошибку ответа, возникающую во время одной из строк .then (response) или в коде php. Я не уверен, что я делаю не так здесь. Любая помощь?!

loginScreen. js

login = () =>{
    const { UserEmail }  = this.state ;
    const { UserPassword }  = this.state ;

    fetch('http://localhost:65535/login.php', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        user_email: UserEmail,
        user_pass: UserPassword
      })
     //Error within line 59-61 or php
    })
    .then((response) => response.json())
    .then((responseJson) => {
        // If server response message same as Data Matched
        if(responseJson === 'Data Matched'){
            alert("Correct");     
        } else{
            alert("Incorrect");
        }

     }).catch((error) => {
         console.error(error);
     });

}


  render() {
    return (
      <View style={styles.container}>
        <ScrollView
          style={styles.container}
          contentContainerStyle={styles.contentContainer}>
          <View style={styles.welcomeContainer}>
            <Image
              source={
                __DEV__
                  ? require('../assets/images/HootLogo.png')
                  : require('../assets/images/robot-prod.png')
              }
              style={styles.welcomeImage}
            />
          </View>

login. php Похоже, все выложено правильно и работает функционально. Я пытался изменить "на" и все.

<?php

 // Importing DBConfig.php file.
 include 'DBConfig.php';

 // Creating connection.
 $con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);

 // Getting the received JSON into $json variable.
 $json = file_get_contents('php://input');

 // decoding the received JSON and store into $obj variable.
 $obj = json_decode($json,true);

 // Populate User email from JSON $obj array and store into $email.
 $user_email = $obj['user_email'];

 // Populate Password from JSON $obj array and store into $password.
 $user_pass = $obj['user_pass'];

 //Applying User Login query with email and password match.
 $Sql_Query = "select * from wp_users where user_email = '$user_email' and user_pass = '$user_pass' ";

 // Executing SQL Query.
 $check = mysqli_fetch_array(mysqli_query($con,$Sql_Query));


 if(isset($check)){
     $SuccessLoginMsg = 'Data Matched';

     // Converting the message into JSON format.
     $SuccessLoginJson = json_encode($SuccessLoginMsg);

     // Echo the message.
     echo $SuccessLoginJson ; 

 } else{

     // If the record inserted successfully then show the message.
     $InvalidMSG = 'Invalid Username or Password Please Try Again' ;

     // Converting the message into JSON format.
     $InvalidMSGJSon = json_encode($InvalidMSG);

     // Echo the message.
     echo $InvalidMSGJSon ;

 }

 mysqli_close($con);
?>

Полный JS Код

import React, { Component } from 'react';
import {
  AppRegistry,
  Image,
  Input, 
  Platform,
  Button,
  Keyboard,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  TextInput,
  View,
} from 'react-native';

import { StackNavigator } from 'react-navigation';



export default class login extends Component {
    static navigationOptions= ({navigation}) =>({
          title: 'Login',   
          headerRight:  

          <TouchableOpacity
            onPress={() => navigation.navigate('Home')}
            style={{backgroundColor: '#f7f7f7'}}>

          </TouchableOpacity>
    });  
    constructor(props){
        super(props)
        this.state={
            userEmail:'',
            userPassword:''
        }
    }

    login = () =>{
    const { UserEmail }  = this.state ;
    const { UserPassword }  = this.state ;

    fetch('http://192.168.0.13:65535/login.php', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({

        user_email: UserEmail,

        user_pass: UserPassword

      })

    }).then((response) => response.json())
          .then((responseJson) => {

            // If server response message same as Data Matched
           if(responseJson === 'Data Matched')
            {

                //Then open Profile activity and send user email to Home After Login. 
                alert(responseJson);

            }
            else{
              alert(responseJson);
            }

          }).catch((error) => {
            console.error(error);
          });

      }


  render() {
    return (
      <View style={styles.container}>
        <ScrollView
          style={styles.container}
          contentContainerStyle={styles.contentContainer}>
          <View style={styles.welcomeContainer}>
            <Image
              source={
                __DEV__
                  ? require('../assets/images/HootLogo.png')
                  : require('../assets/images/robot-prod.png')
              }
              style={styles.welcomeImage}
            />
          </View>

          <View style={styles.errorContainer}>    
            <Text style={{padding:10,margin:10,color:'red'}}>{this.state.email}</Text>
          </View>


          <View style={styles.container}>
              <Text style={styles.headerText}>Username</Text>
          </View>

          <TextInput
          placeholder="Enter Email"
          style={styles.input}
          onChangeText={userEmail => this.setState({userEmail})}
          />

          <View style={styles.container}>
              <Text style={styles.headerText}>Password</Text>
          </View>

          <TextInput
          placeholder="Enter Password"
          style={styles.input}
          secureTextEntry
          onChangeText={userPassword => this.setState({userPassword})}
          />

          <TouchableOpacity style={styles.buttonContainer}
          onPress={this.login}>
          <Text style={styles.buttonText}>Login</Text>
          </TouchableOpacity>

          <View style={styles.loginContainer}>
            <Text style={styles.loginText}>Don't Have an Account?</Text>

            <TouchableOpacity style={styles.emailButtonContainer}
            onPress={() => this.props.navigation.navigate('Links')}>
              <Text style={styles.loginButtonText}>Register</Text>
            </TouchableOpacity>
          </View>


      </ScrollView>
    </View>
  );
  }
}

const styles = StyleSheet.create({
    container: {
    flex: 1,
    backgroundColor: '#fff',
  },

  contentContainer: {
    paddingTop: 10,
  },

  welcomeContainer: {
    alignItems: 'center',
  },

  welcomeImage: {
    width: 250,
    height: 230,
    resizeMode: 'contain',
    marginLeft: -10,
  },

  errorContainer: {
      flex: 1,
      backgroundColor: '#fff',
      marginTop: -55,
      alignSelf: 'center',
    },

  headerText: {
    fontSize: 20,
    color: 'rgba(96,100,109, 1)',
    lineHeight: 24,
    marginLeft: 50,
    marginBottom: 10,
  },

  input: {
    height: 40,
    borderBottomColor: 'rgba(0,0,0,0.4)',
    borderBottomWidth: 3,
    padding: 10,
    marginBottom: 10,
    marginHorizontal: 50,
  },

  buttonContainer: {
    backgroundColor: '#78AA3A',
    padding: 15,
    marginTop: 10,
    marginHorizontal: 50,
    borderColor: '#fff',
    borderRadius:10,
    borderWidth: 1,
  },

  buttonText: {
    textAlign: 'center',
    color: '#FFFFFF',
  },

  loginContainer: {
    textAlign: 'center',
    marginTop: 10,
    flexDirection: 'row',
  },

  loginText: {
    marginLeft: 80,
    marginBottom: 20,
    color: 'rgba(0,0,0,0.4)',
    fontSize: 14,
    lineHeight: 19,
  },

  loginButtonText: {
    fontSize: 14,
    color: '#78AA3A',
    paddingLeft: 5 
  },
});

AppRegistry.registerComponent('login', () => login);

1 Ответ

0 голосов
/ 25 апреля 2020

Из того, что я вижу, проблема в том, что ваш PHP сервер не возвращает действительный json. Он возвращает строку, даже если вы выполните json_encode, строка будет либо "Data Matched", либо "Invalid Username or Password Please Try Again". Однако, когда вы делаете запрос на выборку и делаете

.then((response) => response.json())
          .then((responseJson) => {

Он пытается проанализировать строку «Совпадение данных», когда вы выполняете response.json()).then((responseJson). json () часть пытается проанализировать строку, которая неверен JSON. Таким образом, вы можете решить эту проблему двумя способами, фактически отправив верный json обратно с сервера php, для создания объекта, подобного этому { "success" : true, message :"Data Matched"}, или просто удалите цепочку. json (), поэтому javascript вернет строку и не пытайтесь разобрать его как JSON. Таким образом, без. json () это будет

...
.then((response) => {
           // If server response message same as Data Matched
           if(response === 'Data Matched')
            {
             alert(response);
            } else {
              alert(response);
            }
...

Просто попробуйте сначала удалить .then((response) => response.json() деталь в строке 58 и перейти непосредственно к следующей цепочке, затем пункт

...