React Native 網絡請求封裝:使用Promise封裝fetch請求

React Native中雖然也內置了XMLHttpRequest 網絡請求API(也就是俗稱的ajax),但XMLHttpRequest 是一個設計粗糙的 API,不符合職責分離的原則,配置和調用方式很是混亂,並且基於事件的異步模型寫起來也沒有現代的 Promise 友好。而Fetch 的出現就是爲了解決 XHR 的問題,因此ReactNative官方推薦使用Fetch API。http://blog.csdn.net/withings/article/details/71331726html

fetch請求示例以下:react

1 return fetch('http://facebook.github.io/react-native/movies.json')
2     .then((response) => response.json())
3     .then((responseJson) => {
4       return responseJson.movies;
5     })
6     .catch((error) => {
7       console.error(error);
8     });

Fetch API的詳細介紹及使用說明請參考以下文章:

  • React Native 網絡請求官方文檔git

  • 深刻淺出Fetch APIgithub

  • 傳統 Ajax 已死,Fetch 永生web

  • 【翻譯】這個API很「迷人」——(新的Fetch API)ajax

  • 使用Promise封裝fetch請求

    因爲在項目中不少地方都須要用到網絡請求,爲了使用上的方便,使用ES6的Promise來封裝fetch網絡請求,代碼以下:json

  •  1 let common_url = 'http://192.168.1.1:8080/';  //服務器地址
     2 let token = '';   
     3 /**
     4  * @param {string} url 接口地址
     5  * @param {string} method 請求方法:GET、POST,只能大寫
     6  * @param {JSON} [params=''] body的請求參數,默認爲空
     7  * @return 返回Promise
     8  */
     9 function fetchRequest(url, method, params = ''){
    10     let header = {
    11         "Content-Type": "application/json;charset=UTF-8",
    12         "accesstoken":token  //用戶登錄後返回的token,某些涉及用戶數據的接口須要在header中加上token
    13     };
    14     console.log('request url:',url,params);  //打印請求參數
    15     if(params == ''){   //若是網絡請求中帶有參數
    16         return new Promise(function (resolve, reject) {
    17             fetch(common_url + url, {
    18                 method: method,
    19                 headers: header
    20             }).then((response) => response.json())
    21                 .then((responseData) => {
    22                     console.log('res:',url,responseData);  //網絡請求成功返回的數據
    23                     resolve(responseData);
    24                 })
    25                 .catch( (err) => {
    26                     console.log('err:',url, err);     //網絡請求失敗返回的數據        
    27                     reject(err);
    28                 });
    29         });
    30     }else{   //若是網絡請求中沒有參數
    31         return new Promise(function (resolve, reject) {
    32             fetch(common_url + url, {
    33                 method: method,
    34                 headers: header,
    35                 body:JSON.stringify(params)   //body參數,一般須要轉換成字符串後服務器才能解析
    36             }).then((response) => response.json())
    37                 .then((responseData) => {
    38                     console.log('res:',url, responseData);   //網絡請求成功返回的數據
    39                     resolve(responseData);
    40                 })
    41                 .catch( (err) => {
    42                     console.log('err:',url, err);   //網絡請求失敗返回的數據  
    43                     reject(err);
    44                 });
    45         });
    46     }
    47 }

    使用fetch請求,若是服務器返回的中文出現了亂碼,則能夠在服務器端設置以下代碼解決: 
    produces="text/html;charset=UTF-8"react-native

    fetchRequest使用以下:

      • GET請求:
  •  1 fetchRequest('app/book','GET')
     2     .then( res=>{
     3         //請求成功
     4         if(res.header.statusCode == 'success'){
     5             //這裏設定服務器返回的header中statusCode爲success時數據返回成功
     6  
     7         }else{
     8             //服務器返回異常,設定服務器返回的異常信息保存在 header.msgArray[0].desc
     9             console.log(res.header.msgArray[0].desc);
    10         }
    11     }).catch( err=>{ 
    12         //請求失敗
    13     })
  • POST請求:
  •  1 let params = {
     2     username:'admin',
     3     password:'123456'
     4 }
     5 fetchRequest('app/signin','POST',params)
     6     .then( res=>{
     7         //請求成功
     8         if(res.header.statusCode == 'success'){
     9             //這裏設定服務器返回的header中statusCode爲success時數據返回成功
    10  
    11         }else{
    12             //服務器返回異常,設定服務器返回的異常信息保存在 header.msgArray[0].desc 
    13             console.log(res.header.msgArray[0].desc);
    14         }
    15     }).catch( err=>{ 
    16         //請求失敗
    17     })

    fetch超時處理

    因爲原生的Fetch API 並不支持timeout屬性,若是項目中須要控制fetch請求的超時時間,能夠對fetch請求進一步封裝實現timeout功能,代碼以下:api

    fetchRequest超時處理封裝

  •  1 /**
     2  * 讓fetch也能夠timeout
     3  *  timeout不是請求鏈接超時的含義,它表示請求的response時間,包括請求的鏈接、服務器處理及服務器響應回來的時間
     4  * fetch的timeout即便超時發生了,本次請求也不會被abort丟棄掉,它在後臺仍然會發送到服務器端,只是本次請求的響應內容被丟棄而已
     5  * @param {Promise} fetch_promise    fetch請求返回的Promise
     6  * @param {number} [timeout=10000]   單位:毫秒,這裏設置默認超時時間爲10秒
     7  * @return 返回Promise
     8  */
     9 function timeout_fetch(fetch_promise,timeout = 10000) {
    10     let timeout_fn = null; 
    11  
    12     //這是一個能夠被reject的promise
    13     let timeout_promise = new Promise(function(resolve, reject) {
    14         timeout_fn = function() {
    15             reject('timeout promise');
    16         };
    17     });
    18  
    19     //這裏使用Promise.race,以最快 resolve 或 reject 的結果來傳入後續綁定的回調
    20     let abortable_promise = Promise.race([
    21         fetch_promise,
    22         timeout_promise
    23     ]);
    24  
    25     setTimeout(function() {
    26         timeout_fn();
    27     }, timeout);
    28  
    29     return abortable_promise ;
    30 }
    31  
    32 let common_url = 'http://192.168.1.1:8080/';  //服務器地址
    33 let token = '';   
    34 /**
    35  * @param {string} url 接口地址
    36  * @param {string} method 請求方法:GET、POST,只能大寫
    37  * @param {JSON} [params=''] body的請求參數,默認爲空
    38  * @return 返回Promise
    39  */
    40 function fetchRequest(url, method, params = ''){
    41     let header = {
    42         "Content-Type": "application/json;charset=UTF-8",
    43         "accesstoken":token  //用戶登錄後返回的token,某些涉及用戶數據的接口須要在header中加上token
    44     };
    45     console.log('request url:',url,params);  //打印請求參數
    46     if(params == ''){   //若是網絡請求中帶有參數
    47         return new Promise(function (resolve, reject) {
    48             timeout_fetch(fetch(common_url + url, {
    49                 method: method,
    50                 headers: header
    51             })).then((response) => response.json())
    52                 .then((responseData) => {
    53                     console.log('res:',url,responseData);  //網絡請求成功返回的數據
    54                     resolve(responseData);
    55                 })
    56                 .catch( (err) => {
    57                     console.log('err:',url, err);     //網絡請求失敗返回的數據        
    58                     reject(err);
    59                 });
    60         });
    61     }else{   //若是網絡請求中沒有參數
    62         return new Promise(function (resolve, reject) {
    63             timeout_fetch(fetch(common_url + url, {
    64                 method: method,
    65                 headers: header,
    66                 body:JSON.stringify(params)   //body參數,一般須要轉換成字符串後服務器才能解析
    67             })).then((response) => response.json())
    68                 .then((responseData) => {
    69                     console.log('res:',url, responseData);   //網絡請求成功返回的數據
    70                     resolve(responseData);
    71                 })
    72                 .catch( (err) => {
    73                     console.log('err:',url, err);   //網絡請求失敗返回的數據  
    74                     reject(err);
    75                 });
    76         });
    77     }
    78 }

    加入超時處理的fetchRequest網絡請求的使用方法跟沒加入超時處理同樣。 
    對於fetch網絡請求的超時處理的封裝參考下面這篇文章而寫:promise

    讓fetch也能夠timeout

相關文章
相關標籤/搜索