首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取react本机错误"json parse error意外的eof“

获取react本机错误"json parse error意外的eof“
EN

Stack Overflow用户
提问于 2019-06-27 14:35:47
回答 2查看 3.6K关注 0票数 2

我遵循了站点"http://carlofontanos.com/user-login-with-wordpress-using-react-native/“中的代码。

我已经这样做了我的Login.js

代码语言:javascript
复制
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;
  }
}

我已经像这样做了服务器站点的代码。

*

代码语言:javascript
复制
<?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 parse error意外的eof“。你可以在php代码中,我已经尝试过通过json_encode返回数据。这也不起作用。我能弄点这个吗。我想知道确切的错误在哪里?提前谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-10-24 01:21:30

json-parse-error-unexpected eof它通常是

当您尝试将不可覆盖的响应转换为json (如html响应)为json时出现错误。

为了安全起见,我通常首先使用.then(res => res.text())将其转换为字符串,然后使用console.log()或alert()来证明响应是否可以转换为json,而不会显示react-native的红盒消息。

如果响应是有效的json,您可以使用JSON.parse(responseText)自己转换它

票数 1
EN

Stack Overflow用户

发布于 2021-10-26 10:32:13

我的问题是,这是错误的原因,对于我来说,某一次的and服务,我调用了另一次,这是没有问题的,不需要更改代码!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56785228

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档