Получение ошибки при реагировании на "json parse error непредвиденный eof" - PullRequest
0 голосов
/ 27 июня 2019

Я следовал этому коду с сайта "http://carlofontanos.com/user-login-with-wordpress-using-react-native/"

Я сделал свои Login.js вот так

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TextInput,
  TouchableOpacity,
  Keyboard
} from 'react-native';
import { AsyncStorage } from 'react-native';
import {Actions} from 'react-native-router-flux';
import { StackNavigator } from 'react-navigation';
export default class LoginForm extends Component<{}> {

  constructor(props){
    super(props)
    this.state={
      userEmail:'',
      userPassword:'',
      validating: false
    }
  }

  login = () =>{
    this.state.validating = true;
    const {userEmail,userPassword} = this.state;
    let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/ ;
    if(userEmail==""){
      //alert("Please enter Email address");
      this.setState({email:'Please enter Email address'})

    }

    else if(reg.test(userEmail) === false)
    {
    //alert("Email is Not Correct");
    this.setState({email:'Email is Not Correct'})
    return false;
      }

    else if(userPassword==""){
    this.setState({email:'Please enter password'})
    }
    else{

    fetch('http://siteURL/wetest/userlogin.php',{
      method:'post',
      header:{
        'Accept': 'application/json',
        'Content-type': 'application/json'
      },
      body:JSON.stringify({
        email: userEmail,
        password: userPassword
      })

    })
    .then((response) => response.json())
     .then((responseJson)=>{
        let data = responseJson.data;
        if (this.saveToStorage(data)){
          this.setState({
            validating: false
          });
          alert("Successfully Login");
          /* Redirect to home page */
          Actions.home()
        } else {
          alert("Wrong Login Details");
        }

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


    Keyboard.dismiss();
  }
    render(){
        return(
            <View style={styles.container}>
          <TextInput style={styles.inputBox} 
              underlineColorAndroid='rgba(0,0,0,0)' 
              placeholder="Email"
              placeholderTextColor = "#ffffff"
              selectionColor="#fff"
              keyboardType="email-address"
              onChangeText={userEmail => this.setState({userEmail})}
              />
          <TextInput style={styles.inputBox} 
              underlineColorAndroid='rgba(0,0,0,0)' 
              placeholder="Password"
              secureTextEntry={true}
              placeholderTextColor = "#ffffff"
              ref={(input) => this.password = input}
              onChangeText={userPassword => this.setState({userPassword})}
              />  
           <TouchableOpacity style={styles.button} onPress={this.login} >
             <Text style={styles.buttonText}>Login</Text>
           </TouchableOpacity>     
        </View>
            )
    }

  async saveToStorage(userData){
    if (userData) {
      await AsyncStorage.setItem('user', JSON.stringify({
          isLoggedIn: true,
          authToken: userData.auth_token,
          id: userData.user_id,
          name: userData.user_login
        })
      );
      return true;
    }

    return false;
  }
}

И я сделал код сайта сервера вот так.

*

<?php 
    include 'wp-load.php';
    $json = file_get_contents('php://input');   
    $obj = json_decode($json,true);
    $email = $obj['email'];

    $password = $obj['password'];
$response = array(
    'data'      => array(),
    'msg'       => 'Invalid email or password',
    'status'    => false
);  
    if($obj['email']!=""){  
    $creds = array();
    $creds['user_login'] = $email;
    $creds['user_password'] = $password;
    $creds['remember'] = true;

    $user = wp_signon( $creds, false );

        if ( is_wp_error($user) ){
            echo json_encode('Wrong Details');              
        }
        else{
            $user = get_user_by( 'email', $email );     
            if ( $user ){
                $password_check = wp_check_password( $_POST['password'], $user->user_pass, $user->ID );

                if ( $password_check ){
                    /* Generate a unique auth token */
                    $token = wp_generate_password( 30 );

                    /* Store / Update auth token in the database */
                    if( update_user_meta( $user->ID, 'auth_token', $token ) ){

                        /* Return generated token and user ID*/
                        $response['status'] = true;
                        $response['data'] = array(
                            'auth_token'    =>  $token,
                            'user_id'       =>  $user->ID,
                            'user_login'    =>  $user->user_login
                        );
                        $response['msg'] = 'Successfully Authenticated';
                        //echo json_encode($response);  
                    }
                }
            }           
        }
    }   
    else{
      echo json_encode('try again');
    }

?>

*

Если вы видите оба кода, они написаны для входа в систему и сохраняют данные на устройстве с помощью «async saveToStorage». Но дляТеперь он дает мне ошибку. Ошибка «ошибка синтаксического анализа json eof». Вы можете в коде php, я пытался вернуть данные по json_encode. Это также не сработало. Могу ли я получить некоторые по этому. Я хочузнать, где точная ошибка? Заранее спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...