如何解决React-Native获取API问题#react-native
嗨,大家好,
请您帮我解决React-Native中此登录页面的错误吗?
错误:
无法获取api,也无法从api获得响应,但可以使用硬编码凭据登录,也可以使用正文“ empId”和“ password”使用任何登录凭据。
上面提到的是错误,因此请帮助我使用登录api成功登录。
import React,{ useState } from 'react';
import {
StyleSheet,TextInput,View,Text,ScrollView,Image,Keyboard,TouchableOpacity,KeyboardAvoidingView,ActivityIndicator} from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import Loader from './Components/loader';
const LoginScreen = props => {
let [userEmail,setUserEmail] = useState('');
let [userPassword,setUserPassword] = useState('');
let [loading,setLoading] = useState(false);
let [errortext,setErrortext] = useState('');
const handleSubmitPress = () => {
setErrortext('');
if (!userEmail) {
alert('Please fill Email');
return;
}
if (!userPassword) {
alert('Please fill Password');
return;
}
setLoading(true);
var dataToSend = { empld: userEmail,password: userPassword };
var formBody = [];
for (var key in dataToSend) {
var encodedKey = encodeURIComponent(key);
var encodedValue = encodeURIComponent(dataToSend[key]);
formBody.push(encodedKey + '=' + encodedValue);
}
formBody = formBody.join('&');
fetch('BaseURL',{
method: 'POST',body: formBody,headers: {
'Content-Type': 'application/json',},// tried some hardcoded value
body: {
empld: 'E10008',password: 'Pass@12345'
}
})
.then(response => console.log(response))
.then(response => response.json())
.then(responseJson => {
setLoading(false);
console.log(responseJson);
if (responseJson.status == 0) {
AsyncStorage.setItem('user_id',responseJson.data[0].user_id);
console.log(responseJson.data[0].user_id);
props.navigation.navigate('DrawerNavigationRoutes');
} else {
setErrortext('Please check your email id or password');
console.log('Please check your email id or password');
}
})
.catch(error => {
setLoading(false);
console.error(error);
});
};
return (
<View style={styles.mainBody}>
<Loader loading={loading} />
<ScrollView keyboardShouldPersistTaps="handled">
<View style={{ marginTop: 100 }}>
<KeyboardAvoidingView enabled>
<View style={{ alignItems: 'center' }}>
<Image
source={require('../Image/aboutreact.png')}
style={{
width: '90%',height: 80,resizeMode: 'contain',margin: 30,}}
/>
</View>
<View style={styles.SectionStyle}>
<TextInput
style={styles.inputStyle}
onChangeText={UserEmail => setUserEmail(UserEmail)}
placeholder="Enter Email" //dummy@abc.com
placeholderTextColor="#FFFFFF"
autoCapitalize="none"
keyboardType="email-address"
ref={ref => {
this._emailinput = ref;
}}
returnKeyType="next"
onSubmitEditing={() =>
this._passwordinput && this._passwordinput.focus()
}
blurOnSubmit={false}
/>
</View>
<View style={styles.SectionStyle}>
<TextInput
style={styles.inputStyle}
onChangeText={UserPassword => setUserPassword(UserPassword)}
placeholder="Enter Password" //12345
placeholderTextColor="#FFFFFF"
keyboardType="default"
ref={ref => {
this._passwordinput = ref;
}}
onSubmitEditing={Keyboard.dismiss}
blurOnSubmit={false}
secureTextEntry={true}
/>
</View>
{errortext != '' ? (
<Text style={styles.errorTextStyle}> {errortext} </Text>
) : null}
<TouchableOpacity
style={styles.buttonStyle}
activeOpacity={0.5}>
<Text style={styles.buttonTextStyle}
onPress={handleSubmitPress}>LOGIN</Text>
</TouchableOpacity>
<Text
style={styles.registerTextStyle}
onPress={() => props.navigation.navigate('RegisterScreen')}>
Don't have an account yet? Register Here
</Text>
</KeyboardAvoidingView>
</View>
</ScrollView>
</View>
);
};
export default LoginScreen;
const styles = StyleSheet.create({
mainBody: {
flex: 1,justifyContent: 'center',backgroundColor: '#455a64',SectionStyle: {
flexDirection: 'row',height: 40,marginTop: 20,marginLeft: 35,marginRight: 35,margin: 10,buttonStyle: {
backgroundColor: '#5D6D7E',borderWidth: 0,color: '#FFFFFF',borderColor: '#7DE24E',alignItems: 'center',borderRadius: 30,marginBottom: 20,buttonTextStyle: {
color: '#FFFFFF',paddingVertical: 10,fontSize: 16,inputStyle: {
flex: 1,width:300,backgroundColor: 'rgba(255,255,0.3)',paddingLeft: 25,paddingRight: 15,borderWidth: 1,borderColor: 'white',fontSize: 16
},registerTextStyle: {
color: '#FFFFFF',textAlign: 'center',fontWeight: 'bold',fontSize: 15,errorTextStyle: {
color: 'red',fontSize: 14,});
解决方法
不确定为什么要使用'&'联接数据。从硬编码值可以看出,主体对象的正确格式为:
body: {
empld: USERNAME,password: PASSWORD
}
因此,只需发送您的对象dataToSend
,而无需您的formData
对象:
var dataToSend = { empld: userEmail,password: userPassword }
fetch('BaseURL',{
method: 'POST',body: dataToSend,headers: {
'Content-Type': 'application/json',},).then(.....)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。