React Native 网络请求封装:使用 Promise 封装 fetch 请求

5,458 阅读4分钟

React Native中虽然也内置了XMLHttpRequest 网络请求API(也就是俗称的ajax),但XMLHttpRequest 是一个设计粗糙的 API,不符合职责分离的原则,配置和调用方式非常混乱,而且基于事件的异步模型写起来也没有现代的 Promise 友好。而Fetch 的出现就是为了解决 XHR 的问题,所以React Native官方推荐使用Fetch API。

fetch请求示例如下:

return fetch('http://facebook.github.io/react-native/movies.json')
    .then((response) => response.json())
    .then((responseJson) => {
      return responseJson.movies;
    })
    .catch((error) => {
      console.error(error);
    });

Fetch API的详细介绍及使用说明请参考如下文章:

使用Promise封装fetch请求

由于在项目中很多地方都需要用到网络请求,为了使用上的方便,使用ES6的Promise来封装fetch网络请求,代码如下:

let common_url = 'http://192.168.1.1:8080/';  //服务器地址
let token = '';   
/**
 * @param {string} url 接口地址
 * @param {string} method 请求方法:GET、POST,只能大写
 * @param {JSON} [params=''] body的请求参数,默认为空
 * @return 返回Promise
 */
function fetchRequest(url, method, params = ''){
    let header = {
        "Content-Type": "application/json;charset=UTF-8",
        "accesstoken":token  //用户登陆后返回的token,某些涉及用户数据的接口需要在header中加上token
    };
    console.log('request url:',url,params);  //打印请求参数
    if(params == ''){   //如果网络请求中带有参数
        return new Promise(function (resolve, reject) {
            fetch(common_url + url, {
                method: method,
                headers: header
            }).then((response) => response.json())
                .then((responseData) => {
                    console.log('res:',url,responseData);  //网络请求成功返回的数据
                    resolve(responseData);
                })
                .catch( (err) => {
                    console.log('err:',url, err);     //网络请求失败返回的数据        
                    reject(err);
                });
        });
    }else{   //如果网络请求中没有参数
        return new Promise(function (resolve, reject) {
            fetch(common_url + url, {
                method: method,
                headers: header,
                body:JSON.stringify(params)   //body参数,通常需要转换成字符串后服务器才能解析
            }).then((response) => response.json())
                .then((responseData) => {
                    console.log('res:',url, responseData);   //网络请求成功返回的数据
                    resolve(responseData);
                })
                .catch( (err) => {
                    console.log('err:',url, err);   //网络请求失败返回的数据  
                    reject(err);
                });
        });
    }
}

使用fetch请求,如果服务器返回的中文出现了乱码,则可以在服务器端设置如下代码解决:
produces="text/html;charset=UTF-8"

fetchRequest使用如下:

  • GET请求:
fetchRequest('app/book','GET')
    .then( res=>{
        //请求成功
        if(res.header.statusCode == 'success'){
            //这里设定服务器返回的header中statusCode为success时数据返回成功

        }else{
            //服务器返回异常,设定服务器返回的异常信息保存在 header.msgArray[0].desc
            console.log(res.header.msgArray[0].desc);
        }
    }).catch( err=>{ 
        //请求失败
    })
  • POST请求:
let params = {
    username:'admin',
    password:'123456'
}
fetchRequest('app/signin','POST',params)
    .then( res=>{
        //请求成功
        if(res.header.statusCode == 'success'){
            //这里设定服务器返回的header中statusCode为success时数据返回成功

        }else{
            //服务器返回异常,设定服务器返回的异常信息保存在 header.msgArray[0].desc 
            console.log(res.header.msgArray[0].desc);
        }
    }).catch( err=>{ 
        //请求失败
    })


fetch超时处理

由于原生的Fetch API 并不支持timeout属性,如果项目中需要控制fetch请求的超时时间,可以对fetch请求进一步封装实现timeout功能,代码如下:

fetchRequest超时处理封装

/**
 * 让fetch也可以timeout
 *  timeout不是请求连接超时的含义,它表示请求的response时间,包括请求的连接、服务器处理及服务器响应回来的时间
 * fetch的timeout即使超时发生了,本次请求也不会被abort丢弃掉,它在后台仍然会发送到服务器端,只是本次请求的响应内容被丢弃而已
 * @param {Promise} fetch_promise    fetch请求返回的Promise
 * @param {number} [timeout=10000]   单位:毫秒,这里设置默认超时时间为10秒
 * @return 返回Promise
 */
function timeout_fetch(fetch_promise,timeout = 10000) {
    let timeout_fn = null; 

    //这是一个可以被reject的promise
    let timeout_promise = new Promise(function(resolve, reject) {
        timeout_fn = function() {
            reject('timeout promise');
        };
    });

    //这里使用Promise.race,以最快 resolve 或 reject 的结果来传入后续绑定的回调
    let abortable_promise = Promise.race([
        fetch_promise,
        timeout_promise
    ]);

    setTimeout(function() {
        timeout_fn();
    }, timeout);

    return abortable_promise ;
}

let common_url = 'http://192.168.1.1:8080/';  //服务器地址
let token = '';   
/**
 * @param {string} url 接口地址
 * @param {string} method 请求方法:GET、POST,只能大写
 * @param {JSON} [params=''] body的请求参数,默认为空
 * @return 返回Promise
 */
function fetchRequest(url, method, params = ''){
    let header = {
        "Content-Type": "application/json;charset=UTF-8",
        "accesstoken":token  //用户登陆后返回的token,某些涉及用户数据的接口需要在header中加上token
    };
    console.log('request url:',url,params);  //打印请求参数
    if(params == ''){   //如果网络请求中带有参数
        return new Promise(function (resolve, reject) {
            timeout_fetch(fetch(common_url + url, {
                method: method,
                headers: header
            })).then((response) => response.json())
                .then((responseData) => {
                    console.log('res:',url,responseData);  //网络请求成功返回的数据
                    resolve(responseData);
                })
                .catch( (err) => {
                    console.log('err:',url, err);     //网络请求失败返回的数据        
                    reject(err);
                });
        });
    }else{   //如果网络请求中没有参数
        return new Promise(function (resolve, reject) {
            timeout_fetch(fetch(common_url + url, {
                method: method,
                headers: header,
                body:JSON.stringify(params)   //body参数,通常需要转换成字符串后服务器才能解析
            })).then((response) => response.json())
                .then((responseData) => {
                    console.log('res:',url, responseData);   //网络请求成功返回的数据
                    resolve(responseData);
                })
                .catch( (err) => {
                    console.log('err:',url, err);   //网络请求失败返回的数据  
                    reject(err);
                });
        });
    }
}

加入超时处理的fetchRequest网络请求的使用方法跟没加入超时处理一样。
对于fetch网络请求的超时处理的封装参考下面这篇文章而写:

让fetch也可以timeout