Android fetch 局域网,React Native Android Fetch failing on connection to local API

本文介绍了一个使用React Native创建的简单登录组件示例。该组件通过fetch API向本地服务器发送POST请求进行用户验证,并利用AsyncStorage存储已验证的用户名。示例中还包含了如何设置逆向代理以实现本地开发环境的调试。
摘要由CSDN通过智能技术生成

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

adb -s 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 (

- WELCOME -

onChangeText={(username)=>this.setState({username})}

value={this.state.username}>

onChangeText={(password)=>this.setState({password})}

value={this.state.password}>

LOGIN

);

}

}

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:

83bce2f9e1f117e189acac8b22a3405d.pngfb695c6bb3a379271dc31706abfb664c.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值