我试图通过Fetch将数组从PHP返回到React Native。只要返回的变量是单个变量,它就可以正常工作,但是当我返回一个数组时,响应将为空。
我的PHP代码
header("Access-Control-Allow-Origin: *");
if(isset($_POST) && !empty($_POST)){
}else{
parse_str($_SERVER['REDIRECT_QUERY_STRING'], $get_array);
$_GET = (array) $get_array;
$_POST = (array) json_decode(file_get_contents('php://input'));
}
$to_return = array();
if(isset($_GET['token']) && $_GET['token'] != ''){
if(check_token($_GET['token'])){
if(isset($_POST['email']) && $_POST['email'] != '' && isset($_POST['password']) && $_POST['password'] != ''){
$user = wp_authenticate( $_POST['email'], $_POST['password'] );
if($user){
$token = md5(uniqid(rand(), true));
delete_user_meta( $user->ID, 'api_token');
add_user_meta( $user->ID, 'api_token', $token);
$to_return['token'] = $token;
$to_return['result'] = 'user logged in successfully';
}else{
$to_return['result'] = 'user not authorized';
}
}else{
$to_return['result'] = 'parameters are missing2';
}
}else{
$to_return['result'] = 'invalid token';
}
}else{
$to_return['result'] = 'parameters are missing1';
}
//this line works fine
echo json_encode($to_return['token']);
//this line gives emoty response
echo json_encode($to_return);
我的React Native代码:
import React from 'react';
import { View, Text, Button, TextInput, AsyncStorage, StyleSheet } from 'react-native';
import FormData from 'FormData';
class LoginScreen extends React.Component {
login = () => {
url = 'https://foodtest.cloudaccess.host/wp-json/v1/login_customer?token=********';
var object = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: '**********@network-source.com',
password: '*******',
})
};
fetch(url, object)
.then((response) => response.json())
.then((responseData) => { console.log(responseData); })
.catch((err) => { console.log(err); });
}
render() {
return (
<View style={styles.container}>
<Text>Login Screen</Text>
<View style={styles.field_cont}>
<Text>Email</Text>
<TextInput
style={{ height: 40, borderColor: 'gray', borderWidth: 1, width: '100%' }}
/>
</View>
<View style={styles.field_cont}>
<Text>Password</Text>
<TextInput
style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
/>
</View>
<Button
title="Login"
color="#841584"
accessibilityLabel="Login"
onPress={this.login}
/>
</View>
);
}
}
export default LoginScreen;
const styles = StyleSheet.create({
container: {
flex: 1,
width: '100%',
height: 100,
justifyContent: 'center',
alignItems: 'center'
},
field_cont: {
padding: 10,
width: '100%'
}
});
我正在使用Reactotron查看返回值。在PHP的第二行显示为空,并且成功显示了单个变量。
答案 0 :(得分:1)
可能是因为JSON的解析很奇怪,请尝试response.text()
并查看JSON字符串如何返回。
还要为content type application/json
添加一个PHP标头,以查看是否有区别。