React Native Fetch网络请求的封装

2017-07-18  本文已影响603人  Har_vey

一、语法:

fetch(参数)
  .then(完成的回调函数)
  .catch(失败的回调函数)


fetch(url,opts) 
.then((response) => { 
//请求成功后返回的对象response 
//例如:json、text等 
return response.text(); 
return response.json(); 
}) 
.then((responseData) => { 
//处理请求得到的数据 
}) 
.catch((error) => { 
//网络请求失败执行该回调函数,得到错误信息 
})

二、网络请求的封装。
首先,我们创建一个BaseRequest.js,所有的网络请求都调用这个文件里的基类方法。直接上代码:


const baseUrl = '';
const timeoutSeconds = 20;
export default class BaseRequest{
    /// POST方法
    static postData(url,parame){
        let p1 = new Promise((resolve,reject)=>{
            fetch(url,{
                mthods:'POST',
                ///请求头参数
                headers:{
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
                /// 请求参数
                body:JSON.stringify(parame)
            })
            .then((response)=>response.json())
            .then((responseJson)=>{
                /// 拿到数据可以在此同意处理服务器返回的信息
                resolve(responseJson);
            })
            .catch((error)=>{
                reject(error);
            })
        })

        let p2 = this.requestTimeout();
        /// 因为fetch网络请求没有超时时间设置,所以使用Promise实现请求超时
        return Promise.race([p1,p2])
    }

    /// Get方法
    static getData(url,parame){
        let p1= new Promise((resolve,rejcet)=>{
            fetch(url)
            .then((response)=>response.json())
            .then((responseJson)=>{
                /// 拿到数据可以在此同意处理服务器返回的信息
                resolve(responseJson);
            })
            .catch((error)=>{
                reject(error);
            })
        })
        let p2 = this.requestTimeout();
        return Promise.race([p1,p2]);
    }

    /// 设置超时的方法
    static requestTimeout(){
        return new Promise((resolve,reject)=>{
            setTimeout(()=>{
                reject('链接超时');
            },timeoutSeconds * 1000)
        })
    }
}

三、调用BaseRequest

import BaseRequest from './BaseRequest'

componentDidMount(){
    BaseRequest.getData('https://facebook.github.io/react-native/movies.json')
    .then((data)=>{
      console.log(data);
    })
    .catch(error=>{
      console.log(error);
    })

    BaseRequest.postData('https://mywebsite.com/endpoint/',{
      firstParam: 'yourValue',
      secondParam: 'yourOtherValue',
    })
    .then((data)=>{
      console.log(data);
    })
    .catch(error=>{
      console.log(error);
    })
    
  }
上一篇下一篇

猜你喜欢

热点阅读