React Native网络请求 fetch

作者: 天方夜歌 | 来源:发表于2018-05-02 16:22 被阅读149次

    我们在项目中经常会用到HTTP请求来访问网络,HTTP(HTTPS)请求通常分为"GET"、"POST"、"DELETE"、"PATCH",如果不指定默认为GET请求,上面这四种请求方式是我常用的。

    在项目中我们常用到的一般为GET和POST两种请求方式,其它方式也经常用到,针对带参数的表单提交这类的请求,我们通常会使用POST的请求方式。

    为了发出HTTP请求,我们需要使用到 React Native 提供的 Fetch API 来进行实现。要从任意地址获取内容的话,只需简单地将网址作为参数传递给fetch方法即可(fetch这个词本身也就是获取的意思)

    GET

    如果你想要通过 GET 方法去请求数据并转化成 JSON,可以通过如下代码实现:

    fetch('https://facebook.github.io/react-native/movies.json')
          .then((response) => response.json())
          .then((responseJson) => {
            return responseJson.movies; //处理数据
          })
          .catch((error) => {
            console.error(error); //错误信息
          });
    
    

    通过上面的请求把返回的 Response 转化成 JSON Object,然后取出 JSON Object 里的 movies 字段。同时,如果发生 Error,如网络不通或访问连接错误等, 会被 .catch 。在正常的情况下,我们可以得到如下结果:

    {
      "title": "The Basics - Networking",
      "description": "Your app fetched this from a remote endpoint!",
      "movies": [
        { "title": "Star Wars", "releaseYear": "1977"},
        { "title": "Back to the Future", "releaseYear": "1985"},
        { "title": "The Matrix", "releaseYear": "1999"},
        { "title": "Inception", "releaseYear": "2010"},
        { "title": "Interstellar", "releaseYear": "2014"}
      ]
    }
    
    

    POST(一)

    当然,上面是最基本的 GET 请求,Fetch还有可选的第二个参数,可以用来定制HTTP请求一些参数。你可以指定Headers参数,或是指定使用POST方法,又或是提交数据等等:Fetch API 还支持自定义 Headers,更换 Method,添加 Body 等。

    let url = "http://www.yousite.com/xxxx.ashx”  
    let params = {"name":"admin","password":"admin"};  
    fetch(url, {
      method: 'POST',
      headers: {//header头
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(params)  //传参
    })
    
    

    上面构建了一个基本的 POST 请求,添加了自己的 Headers:Accept和Content-Type,添加了 Body。

    POST(二)

    let url = "http://www.yousite.com/xxxx.ashx”;  
    let params = "username=admin&password=admin”;  
    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: params,
    }).then((response) => {
        if (response.ok) {
            return response.json();
        }
    }).then((json) => {
        console.log(json)
    }).catch((error) => {
        console.error(error);
    }); 
    
    

    POST(三)推荐

    通过上面两种方法,我们还有一种方式可以发送POST请求,当然这种方式也是被推荐使用的。
    如果你的服务器无法识别上面POST的数据格式,那么可以尝试传统的form格式,示例如下:

    let REQUEST_URL = 'http://www.yousite.com/xxxx.ashx';
    
    // `首先我们需要自己创建一个FormData,来存请求参数`
    
    let parameters = new FormData();
    parameters.append("mt", "30013");
    parameters.append("pg", "1");
    parameters.append('ps', '20');
    
    fetch(REQUEST_URL, {
        method: 'POST',
        body: parameters
    }).then((response) => response.json() )  
      .then((responseData)=>{  
        console.log('responseData',responseData);  
      }) .catch((error) => {
        console.log(error)
    
    })
    
    

    推荐这种方法的好处还有一个,就是可以在FormData中直接传递字节流实现上传图片的功能,代码如下:

    uploadImage(){  
      let formData = new FormData();  
      let file = {uri: uri, type: 'multipart/form-data', name: 'a.jpg'};  
    
      formData.append("images",file);  
    
      fetch(url,{  
        method:'POST',  
        headers:{  
            'Content-Type':'multipart/form-data',  
        },  
        body:formData,  
      })  
      .then((response) => response.text() )  
      .then((responseData)=>{  
    
        console.log('responseData',responseData);  
      })  
      .catch((error)=>{console.error('error',error)});  
    
    }
    
    

    处理服务器的响应数据

    上面的例子演示了如何发起请求。很多情况下,你还需要处理服务器回复的数据。

    处理服务器返回的数据,我们已经在上面第二种和第三种的POST请求中实现了数据的处理。具体代码参考上面的实现代码。

    不完全转载:https://www.jianshu.com/p/34e17452de4a

    相关文章

      网友评论

        本文标题:React Native网络请求 fetch

        本文链接:https://www.haomeiwen.com/subject/yabylftx.html