React-Native Fetch网络请求的简单封装

在react-native开发中,使用Fetch进行网络请求。官方文档上的网络请求html

基本使用方法

GET请求

1 fetch(@"http://www.baidu.com")
2   .then((response) => response.json()) 
3   .then((responseJson) => {
4         console.log(responseJson);//打印返回的数据
5     });
6   })
7   .catch((error)=>{
8         console.log(error);//打印报的错
9   })

catch住fetch可能抛出的异常,不然出错时你可能看不到任何提示。react

POST请求

Fetch还有可选的第二个参数,能够用来定制HTTP请求一些参数。你能够指定header参数,或是指定使用POST方法,又或是提交数据等等:web

 1 fetch('https://mywebsite.com/endpoint/', {
 2   method: 'POST',
 3   headers: {
 4     'Accept': 'application/json',
 5     'Content-Type': 'application/json',
 6   },
 7   body: JSON.stringify({
 8     firstParam: 'yourValue',
 9     secondParam: 'yourOtherValue',
10   })
11 })

若是你的服务器没法识别上面POST的数据格式,那么能够尝试传统的form格式:json

1 fetch('https://mywebsite.com/endpoint/', {
2   method: 'POST',
3   headers: {
4     'Content-Type': 'application/x-www-form-urlencoded',
5   },
6   body: 'key1=value1&key2=value2'
7 })

能够参考Fetch请求文档来查看全部可用的参数。react-native

简单封装

GET

 1 /*
 2      *  get请求
 3      *  url:请求地址
 4      *  params:参数
 5      *  callback:回调函数
 6      * */
 7     static get(url,params,callback){
 8         if (params) {
 9             let paramsArray = [];
10             //拼接参数
11             Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
12             if (url.search(/\?/) === -1) {
13                 url += '?' + paramsArray.join('&')
14             } else {
15                 url += '&' + paramsArray.join('&')
16             }
17         }
18         //fetch请求
19         fetch(url,{
20             method: 'GET',
21         })
22             .then((response) => {
23                 callback(response)
24             })
25             .catch((error) => {
26                 alert(error)
27             });
28     }

POST

post有两种形式:服务器

  • 第一种:’Content-Type’: ‘application/json’
  •  1 /*
     2      *  post请求
     3      *  url:请求地址
     4      *  params:参数,这里的参数格式是:{param1: 'value1',param2: 'value2'}
     5      *  callback:回调函数
     6      * */
     7     static postJSON(url,params,callback){
     8         //fetch请求
     9         fetch(url,{
    10             method: 'POST',
    11             headers: {
    12               'Accept': 'application/json',
    13                 'Content-Type': 'application/json',
    14             },
    15             body:JSON.stringify(params)
    16         })
    17             .then((response) => response.json())
    18             .then((responseJSON) => {
    19                 callback(responseJSON)
    20             })
    21             .catch((error) => {
    22                 console.log("error = " + error)
    23             });
    24     }
    25 1
    26 2
    27 3
    28 4
    29 5
    30 6
    31 7
    32 8
    33 9
    34 10
    35 11
    36 12
    37 13
    38 14
    39 15
    40 16
    41 17
    42 18
    43 19
    44 20
    45 21
    46 22
    47 23
    48 24
    49 第二种: form表单形式
    50 /*
    51      *  post请求
    52      *  url:请求地址
    53      *  params:参数,这里的参数要用这种格式:'key1=value1&key2=value2'
    54      *  callback:回调函数
    55      * */
    56     static postForm(url,params,callback){
    57         //fetch请求
    58         fetch(url,{
    59             method: 'POST',
    60             headers: {
    61                 'Content-Type': 'application/x-www-form-urlencoded',
    62             },
    63             body: params
    64         })
    65             .then((response) => response.json())
    66             .then((responseJSON) => {
    67                 callback(responseJSON)
    68             })
    69             .catch((error) => {
    70                 console.log("error = " + error)
    71             });
    72     }

    调用

  •  1 //post请求
     2         let params = {'key1':'value1','key2':'value2'};
     3         NetRequest.postJSON('http://www.baidu.com/',params,function (set) {
     4             //下面的就是请求来的数据
     5             console.log(set)
     6         })
     7 
     8 //get请求,以百度为例,没有参数,没有header
     9        NetRequest.get('https://www.baidu.com/','',function (set) {
    10             //下面是请求下来的数据
    11             console.log(set)
    12         })

    解释一下:网络

    //将JSON数据转换成字符串 
    JSON.stringify(params)app

    //将数据JSON化 
    JSON.parse(responseJSON)函数