发布到数据库不起作用(Error/Warning:JSON 输入意外结束)

Posting to database doesn't work (Error/Warning: Unexpected end of JSON input)

我正在使用 React Native 开发移动应用程序。问题是我似乎无法向数据库中插入任何内容。我有一个注册页面,用户需要在其中输入用户名和密码(并重复该密码),这在几个月前运行良好。我没有更改那个特定页面上的任何内容,但是当我开始添加新页面时,例如另一个不起作用的页面,它停止工作并给了我可以在这里看到的警告:

另一个不起作用的页面是用户可以 post 带有标题日期等的工作。此页面未完成,但应该完成,以便用户可以 post 数据库的某些内容,但它给了我可以在此处看到的错误:

注册页面的代码如下(不包括样式表):

import React, { Component } from "react"; 
import { View, Text, StyleSheet, Alert, TextInput, ImageBackground, Image, AsyncStorage, TouchableOpacity } from "react-native";
import { Button, Icon, withTheme } from 'react-native-elements';

const SIGNUP_URL = 'http://kamilla-server.000webhostapp.com/app/signUp.php';

class SignUp extends Component {
 constructor(props) {
    super(props);

    this.state= {
        email: '',
        password: '',
        password2: '',
    };
 }

async onSignUp() {
    const { email, password, password2 } = this.state;

    if(this.state.email != '' && this.state.password != '' && this.state.password2 != '') {
        if(password != password2) {
            Alert.alert('Password matcher ikke', 'De to indtastede passwords skal være det samme password')
        } else {
            const response = await fetch(SIGNUP_URL, {
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json'
                },
                method: 'POST',
                body: JSON.stringify({ email, password }),
            })

            const data = await response.json()


            if (data.error) {
                alert(data.error)
            } else {
                AsyncStorage.setItem('UserID', data.user.UserID)
                this.props.navigation.navigate('SignUpMessage')
            }
        }
    } else {
        Alert.alert('Tomme felter', 'Venligt indtast email og password for at kunne oprette en bruger')
    }
}

render() {
    const { email, password, password2 } = this.state;

    return(
        <View style={styles.container}>
            <ImageBackground source={require('../../images/1088.jpg')} style={styles.background} />

            <View>
                <Image source={require('../../../assets/logo.png')} style={styles.logo} />

                <TextInput
                    value={email}
                    onChangeText={(email) => this.setState({email})}
                    placeholder={'Email'}
                    placeholderTextColor='white'
                    keyboardType='email-address'
                    style={styles.input}
                />

                <TextInput
                    value={password2}
                    onChangeText={(password2) => this.setState({ password2 })}
                    placeholder={'Password'}
                    placeholderTextColor='white'
                    secureTextEntry={true}
                    style={styles.input}
                />

                <TextInput
                    value={password}
                    onChangeText={(password) => this.setState({ password })}
                    placeholder={'Password'}
                    placeholderTextColor='white'
                    secureTextEntry={true}
                    style={styles.input}
                />

                <TouchableOpacity onPress={() => this.props.navigation.navigate('Login')}>
                    <Text style={styles.underlined}>Har du allerede en konto? Login.</Text>
                </TouchableOpacity>

                <Button 
                    title="Opret Konto" 
                    buttonStyle={styles.greenButton}
                    onPress={this.onSignUp.bind(this)}
                />

            </View>

        </View>
    )
 }
}

export default SignUp;

URL SIGNUP_URL 链接到以下代码:

<?php
    require_once('../db/dbcon.php');

    session_start();

    try {
        $inputJSON = file_get_contents('php://input');
        $input = json_decode($inputJSON, TRUE);

        $email = htmlspecialchars($input['email']);
        $password = htmlspecialchars($input['password']);

        $dbCon = dbCon($user, $pass);
        $query = $dbCon->prepare("SELECT `user`.Email FROM `user` WHERE `Email` = ?");
        $query->bindParam(1, $email);
        $query->execute();
        $getUser = $query->fetchAll();

        if(count($getUser) > 0) {
            $status = 0;

            echo json_encode(array('error' => 'Der findes allerede en bruger for den indtastede email.'));
        } else {
            $sql = "INSERT INTO `user` (`UserID`, `Email`, `Password`)
                        VALUES (NULL, ?, ?)";
            $query = $dbCon->prepare($sql);
            $query->bindParam(1, $email);
            $query->bindParam(2, $password);

            $query->execute();

            $last_id = $dbCon->lastInsertId();
            $query2 = $dbCon->prepare("SELECT `UserID`
                                    FROM `user`
                                    WHERE `UserID` = '{$last_id}'");
            $query2->execute();
            $getNewUser = $query2->fetch();
            if ($query2) {
                echo json_encode(array('user' => $getNewUser));

                $_SESSION['userID'] = $getUser['UserID'];
                //$_SESSION['volunteerID'] = $getVolunteer['VolunteerID'];

            } else {
                echo json_encode(array('error' => 'Der gik noget galt. Venligst prøv igen.'));
            }
        }
    } catch (PDOException $e) {
        error_log(print_r($e->getMessage(), TRUE));
    }

?>

我在这里可能是错的,但我最好的猜测是你的提取 api 收到错误你应该尝试将 async onSignUp 函数的提取修改为如下内容:

  await fetch(SIGNUP_URL, {<params>})
    .then(res => {
      // Handle API Errors
      if (!res.ok) {
        console.log(res.statusText);
      }
      // Return if no errors
      return res.json();
    })
    // this is the data you want
    .then(data => data)
    // it will only reject on network failure or if anything prevented the request from completing
    .catch(error => {
      console.log(error.message)
    });

你可以试试上面的方法,看看你的响应有没有报错! 希望这对您有所帮助!!

问题出在这一行: $_SESSION['userID'] = $getUser['UserID']; $getUser 需要是 $getNewUser,因为那是我从中获取的变量的名称。我一定是在不知不觉中更改了它,从而造成了问题。