安装 fetch
npm install whatwg-fetch --save
1.fetch的Get方式通讯
async sendGet(){ let response = await fetch('http://192.168.1.138:3000/aa.html'); if(response.ok){ let text = await response.text(); Alert.alert(text); } } render() { return ( <View style={[Layout.top,{flexDirection:'row',justifyContent:'center',alignItems:'center'}]}> <Button onPress={this.sendGet} title="http请求" color="#841584" /> </View> ) }
2.fetch的post方式通讯
1 async sendPost(){ 2 var fetchOptions = { 3 method: 'POST', 4 headers: { 5 'Accept': 'application/json', 6 //表单 7 'Content-Type': 'application/x-www-form-urlencoded' 8 }, 9 body:'email=aaaaaaa&pwd=bbbbbbbbb' 10 }; 11 let response = await fetch('http://192.168.1.138:3000/shop/aa',fetchOptions); 12 let text = await response.text(); 13 Alert.alert(text); 14 } 15 render() { 16 return ( 17 <View style={[Layout.top,{flexDirection:'row',justifyContent:'center',alignItems:'center'}]}> 18 <Button 19 onPress={this.sendPost} 20 title="http请求" 21 color="#841584" 22 /> 23 </View> 24 ) 25 }
3.fetch的二进制post提交
1 async sendBinaryPost(){ 2 var formData = new FormData(); 3 formData.append('email','aa'); 4 formData.append('pwd','bb'); 5 let response = await fetch('http://192.168.1.138:3000/shop/login',{ 6 method:'POST', 7 headers:{}, 8 body:formData 9 }); 10 let text = await response.text(); 11 alert(text); 12 } 13 14 render() { 15 return ( 16 <View style={[Layout.top,{flexDirection:'row',justifyContent:'center',alignItems:'center'}]}> 17 <Button 18 onPress={this.sendBinaryPost} 19 title="http请求" 20 color="#841584" 21 /> 22 </View> 23 ) 24 }