React Native Android Fetch failing on connection to local API

前端 未结 9 1851
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 22:08

I\'m using the fetch API in my react-native Android app to make requests to a local API. I usually query said API from react web apps at http://localhost:8163.

I\'m t

相关标签:
9条回答
  • 2020-11-28 23:00

    Run the below command to access localhost or 127.0.0.1 or your computer's ip

    adb -s <device_name> reverse tcp:backend_port tcp:backend_port
    

    Example:

    adb -s emulator-5554 reverse tcp:3000 tcp:3000
    

    Now, You can use like below in your component.

    import React from 'react';
    import {View,Image,TextInput, TouchableOpacity, StyleSheet, ImageBackground, AsyncStorage} from 'react-native';
    import {Text,Button} from 'native-base';
        export class Login extends React.Component{
        constructor(props){
            super(props);
            this.state={username:'',password:''}
          }
          login = () =>{
            fetch('http://localhost:3000/users',{
              method:'POST',
                headers:{
                  'Accept':'application/json',
                  'Content-Type':'application/json'
                },
                body:JSON.stringify({
                  username:this.state.username,
                  password:this.state.password
                })
            })
            .then((response)=>response.json())
            .then((res)=>{
              if(res.success===true){
                var username=res.message;
                AsyncStorage.setItem('username',username);
                this.props.navigation.navigate('app');
                alert("Login success");
              } else{
                alert("Invalid Credentials");
              }
            })
            .done();
          }
        render(){
          return (
        <View style={styles.content}>
                    <Text style={styles.logo}>- WELCOME -</Text>
                    <View>
                      <TextInput underlineColorAndroid='transparent' style={styles.input} placeholder="Username"
                      onChangeText={(username)=>this.setState({username})}
                      value={this.state.username}>
                      </TextInput>
                      <TextInput secureTextEntry={true} underlineColorAndroid='transparent' style={styles.input} placeholder="Password"
                      onChangeText={(password)=>this.setState({password})}
                      value={this.state.password}>
                      </TextInput>
                    </View>
                    <TouchableOpacity onPress={this.login} style={styles.buttonContainer}>
                      <Text style={styles.buttonText}>LOGIN</Text>
                    </TouchableOpacity>
                  </View>
        );
        }
        }
        const styles = StyleSheet.create({
          container:{
            flex:1,
          },
          content:{
            opacity:0.9,
            backgroundColor:'white',
            borderWidth:2,
            margin:10,
            alignItems: 'center',
          },
          logo:{
            justifyContent: 'center',
            alignItems: 'center',
            fontSize:45,
            color:'black',
            textShadowColor:'gray',
            textShadowRadius:10
          },
          input:{
            borderRadius:10,
            padding:10,
            color:'black',
            borderWidth:2,
            borderColor:'lightgray',
            width:200,
            margin:5
          },
          buttonContainer:{
            margin:10,
            padding:10,
            justifyContent: 'center',
            alignItems: 'center',
          },
          buttonText:{
            borderRadius:100,
            padding:10,
            backgroundColor:'magenta',
            color:'white',
            textAlign:'center',
            width:100
          }
    
        });
    

    Output:

    0 讨论(0)
  • 2020-11-28 23:05

    Good day, This is working

    I use my machine's IP the Ethernet adapter Ethernet 2: IPV4 Address

    And allow my port on firewall both Inbound and outbound rules

    0 讨论(0)
  • 2020-11-28 23:15

    If you're using expo just copy the URL above QR code and add it to you API instead localhost

    it will like this

    {
      expo host :http://192.168.0.109:{Your Port}/The name for your API
    }
    
    0 讨论(0)
提交回复
热议问题