php - 使用 PHP 的 React-native 总是返回 NULL
问题描述
我正在尝试为我的应用创建一个使用 PHP/MySQL 身份验证的登录名。有人实际上有与我完全相同的帖子。如何将 react-native 与 php 一起使用,获取返回数据始终为 null 我尝试实施建议的更改,因为直到今天我才听说 php://input,但它仍然返回 NULL。我想看看握手是否“打嗝”,所以我配置了一个内置在 MySQL 中的测试表来存储返回的原始数据,以查看服务器是否甚至接收到信息,但每次之后表列总是返回 NULL插入。我正在尝试将 JSON 数据传递给 PHP 脚本,但我想它可能不喜欢它?有没有人有任何想法?
// 我的 login.js 文件的代码
import React from "react";
import { StyleSheet, ScrollView, KeyboardAvoidingView, TouchableOpacity, AsyncStorage, TextInput, Button, View, Text } from 'react-native';
import { createStackNavigator, createAppContainer } from 'react-navigation';
// internal includes...
import styles from '../styles/styles.js'; // styles is the only one lowercase
class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: '',
}
}
// check if the user is already logged in...
componentDidMount() {
this._loadInitialState().done();
}
_loadInitialState = async () => {
var value = await AsyncStorage.getItem('user');
if (value !== null) {
this.props.navigation.navigate('Profile');
}
}
render() {
return (
<KeyboardAvoidingView behavior='padding' style={styles.wrapper}>
<View style={styles.container}>
<Text style={styles.header}> Login </Text>
<TextInput
style={styles.TextInput} placeholder='Username'
onChangeText={ (username) => this.setState({username}) }
underLineColorAndroid='transparent'
/>
<TextInput
style={styles.TextInput} placeholder='Password'
onChangeText={ (password) => this.setState({password}) }
underLineColorAndroid='transparent'
/>
<TouchableOpacity
style={styles.btn}
onPress={this.login}>
<Text> Log In </Text>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
);
}
login = () => {
// check if the username is being passed off properly...
//alert(this.state.username);
fetch('MYWEBSITELINK', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: this.state.username,
password: this.state.password,
})
})
.then(function(response){ return response.json(); }) // transforms response into data that is readable for this app...
.then(function(data) {
console.log(data);
})
}
}
export default Login
// 处理登录请求的 php 文件
<?php
// Access MySQL login information file...
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/live/configuration/mysqli.php";
require_once($path);
// set this in all mobile related files...
header('Content-Type: application/json');
$json = json_decode(file_get_contents('php://input'), true);
// create user record in the login table...
$query = "INSERT INTO test (data)
VALUES (?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('s', $json);
$stmt->execute();
$stmt->close();
?>
编辑 1:我忘记发布我收到的错误/警告,我认为这与我的 JSON 格式有关。“[未处理的承诺拒绝:语法错误:JSON 解析错误:意外的 EOF]”。现在有没有人可以输出我在控制台中发送的响应,以便我可以查看它是否需要重新格式化?谢谢。