【问题标题】:React-Native fetching API issue #react-nativeReact-Native 获取 API 问题 #react-native
【发布时间】:2020-09-10 13:25:29
【问题描述】:

大家好,
请您帮我解决 React-Native 中此登录页面的错误?
错误: strong>
无法获取 api 并且无法从 api 获得响应,但能够使用硬编码凭据以及使用正文“empId”和“密码”的任何登录凭据登录。 上面说的是错误,请帮我用登录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',
    height: 40,
    alignItems: 'center',
    borderRadius: 30,
    marginLeft: 35,
    marginRight: 35,
    marginTop: 20,
    marginBottom: 20,
  },
  buttonTextStyle: {
    color: '#FFFFFF',
    paddingVertical: 10,
    fontSize: 16,
  },
  inputStyle: {
    flex: 1,
    width:300,
    backgroundColor: 'rgba(255, 255, 255, 0.3)',
    paddingLeft: 25,
    paddingRight: 15,
    borderWidth: 1,
    borderRadius: 30,
    borderColor: 'white',
    fontSize: 16
  },
  registerTextStyle: {
    color: '#FFFFFF',
    textAlign: 'center',
    fontWeight: 'bold',
    fontSize: 15,
  },
  errorTextStyle: {
    color: 'red',
    textAlign: 'center',
    fontSize: 14,
  },
});

【问题讨论】:

    标签: reactjs react-native react-native-android native react-native-ios


    【解决方案1】:

    不确定为什么要使用“&”连接数据。从硬编码值可以看出,body 对象的正确格式是:

    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(.....)
    

    【讨论】:

    • 错误是一样的,不像预期的那样需要任何凭据才能登录
    • 感谢您的回复,但没有按预期工作
    猜你喜欢
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 2021-12-10
    • 2020-05-08
    • 2021-08-29
    • 1970-01-01
    相关资源
    最近更新 更多