[英]Connect PHP api to React-Native for User Login
我正在嘗試將我的 PHP api 連接到我的 react-native 項目,以便登錄頁面功能允許用戶登錄。 我還希望用戶在登錄后保持登錄狀態,這就是我使用 AsyncStorage 的原因。 我也嘗試使用 node.js 和 express 連接到我的數據庫,但也未能成功。 有人可以指導我並告訴我哪里出錯了。 還有一種方法可以為 TextInput 設置 2 個 onChangeText,因為當我嘗試實現第二個時,第一個 onChangeText 停止工作。
import React,{Component, useState } from 'react';
import {View,TextInput, StatusBar, Text, StyleSheet,Button, TouchableOpacity, Dimensions, Platform} from 'react-native';
import * as Animatable from 'react-native-animatable';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import Feather from 'react-native-vector-icons/Feather';
import LinearGradient from 'react-native-linear-gradient';
import { AuthContext} from '../components/context';
import AsyncStorage from '@react-native-async-storage/async-storage';
UserLoginFunction = () =>{
const { email } = this.state ;
const { password } = this.state ;
fetch('https://localhost/SparXCard/api/login.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email,
password: password
})
}).then((response) => response.json())
.then((responseJson) => {
// If server response message same as Data Matched
if(responseJson === 'Data Matched')
{
AsyncStorage.setItem('user', res.user);
//Then open Profile activity and send user email to profile activity.
this.props.navigation.navigate('HomeScreen', { Email: email });
}
else{
Alert.alert(responseJson);
}
}).catch((error) => {
console.error(error);
});
}
const SignInScreen = ({navigation}) => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [data, setData] = React.useState({
email:'',
password: '',
check_textInputChange: false,
secureTextEntry: true
});
const {signIn} = React.useContext(AuthContext);
const textInputChange = (val) => {
if(val.length != 0) {
setData({
...data,
email: val,
check_textInputChange: true
});
} else {
setData({
...data,
email: val,
check_textInputChange: false
});
}
}
const handlePasswordChange = (val) => {
setData({
...data,
password: val
});
}
const updateSecureTextEntry = () => {
setData({
...data,
secureTextEntry: !data.secureTextEntry
})
}
const componentDidMount = () => {
this._loadInitialState().done();
}
const _loadInitialState = async () => {
var value = await AsyncStorage.getItem('user')
if(value !== null){
this.props.navigation.navigate('HomeScreen')
}
}
/*User Interface*/
return(
<View style={styles.container}>
<StatusBar backgroundColor='#009387' barStyle='dark-content'/>
<View style={styles.header}>
<Text style={styles.text_header}>Welcome!</Text>
</View>
<Animatable.View style={styles.footer}
animation="fadeInUpBig"
>
<Text style={styles.text_footer}>Email</Text>
<View style={styles.action}>
<FontAwesome name="user-o" color="#ffdf2b" size={20} />
<TextInput
placeholder="Your Email"
placeholderTextColor = "#7a6b02"
style={styles.textInput}
autoCapitalize="none"
/* first onChangeText stops working when second once is implemented */
onChangeText={(val)=>textInputChange(val)}
onChangeText={email => setEmail(email)}
/>
{data.check_textInputChange ?
<Animatable.View animation="bounceIn">
<Feather
name="check-circle"
color="green"
size={20}
/>
</Animatable.View>
: null}
</View>
<Text style={[styles.text_footer, {marginTop: 45}]}>Password</Text>
<View style={styles.action}>
<FontAwesome name="lock" color="#ffdf2b" size={20} />
<TextInput
placeholder="Your Password"
placeholderTextColor = "#7a6b02"
secureTextEntry={data.secureTextEntry ? true : false}
style={styles.textInput}
autoCapitalize="none"
onChangeText={(val)=> handlePasswordChange(val)}
onChangeText={password => setPassword(password)}
/>
<TouchableOpacity onPress={updateSecureTextEntry}>
{data.secureTextEntry ?
<Feather
name="eye-off"
color="grey"
size={20}
/>
:
<Feather
name="eye"
color="grey"
size={20}
/> }
</TouchableOpacity>
</View>
<View style={styles.button}>
<TouchableOpacity style={styles.signIn} onPress={this.login} >
<LinearGradient colors={['#ffdf2b', '#cfb504']} style={styles.signIn}>
<Text style={[styles.textSign,{color:'#161616'}]}>Sign In</Text>
</LinearGradient>
</TouchableOpacity>
<TouchableOpacity onPress={() => navigation.navigate('SignUpScreen')} style={[styles.signIn,
{ borderColor: '#ffdf2b', borderWidth:1, marginTop:20}]}>
<Text style={[styles.textSign,{color:'#ffdf2b'} ]}>Sign Up</Text>
</TouchableOpacity>
</View>
</Animatable.View>
</View>
);
};
/*
login = () => {
fetch('http://localhost:3000/users',{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type' : 'application/json',
},
body: JSON.stringify({
email: this.email,
password: this.password,
})
})
.then((response) => response.json())
.then((res) => {
alert(res.message)
if (res.success === true) {
AsyncStorage.setItem('user', res.user);
this.props.navigation.navigate('HomeScreen');
}
else{
alert(res.message)
}
})
.done();
} */
export default SignInScreen;
我的 PHP email 並登錄 api。
//Define your host here.
$HostName = "localhost";
//Define your database name here.
$DatabaseName = "users";
//Define your database username here.
$HostUser = "root";
//Define your database password here.
$HostPass = "root";
// Creating connection.
$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
// Getting the received JSON into $json variable.
$json = file_get_contents('php://input');
// decoding the received JSON and store into $obj variable.
$obj = json_decode($json,true);
// Populate User email from JSON $obj array and store into $email.
$email = $obj['email'];
// Populate Password from JSON $obj array and store into $password.
$password = $obj['password'];
//Applying User Login query with email and password match.
$Sql_Query = "select * from user where email = '$email' and password = '$password' ";
// Executing SQL Query.
$check = mysqli_fetch_array(mysqli_query($con,$Sql_Query));
if(isset($check)){
$SuccessLoginMsg = 'Data Matched';
// Converting the message into JSON format.
$SuccessLoginJson = json_encode($SuccessLoginMsg);
// Echo the message.
echo $SuccessLoginJson ;
}
else{
// If the record inserted successfully then show the message.
$InvalidMSG = 'Invalid Username or Password Please Try Again' ;
// Converting the message into JSON format.
$InvalidMSGJSon = json_encode($InvalidMSG);
// Echo the message.
echo $InvalidMSGJSon ;
}
mysqli_close($con);
嘗試將 localhost 更改為您的系統 IP(IPv4)/API/端點。 命令提示符並輸入 ipconfig 並在本地測試時使用 HTTP 但在現場測試時需要 Https
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.