zoukankan      html  css  js  c++  java
  • ReactNative http网络通讯

    安装 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 }
  • 相关阅读:
    js上传照片本地预览
    2020年6月23日第一次面试题(外派PA)
    笔记
    2020VUE系统回顾与学习
    2019最全前端面试问题及答案总结
    常见的浏览器兼容性问题总结
    Vue咖啡app项目总结
    跨域问题研究总结
    Class.forName()用法及与new区别
    反射
  • 原文地址:https://www.cnblogs.com/yu-hailong/p/8416967.html
Copyright © 2011-2022 走看看