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

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

基本使用方法

GET请求

fetch(@"http://www.baidu.com")
  .then((response) => response.json()) 
  .then((responseJson) => {
        console.log(responseJson);//打印返回的数据
    });
  })
  .catch((error)=>{
        console.log(error);//打印报的错
  })

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

POST请求

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

fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  })
})

如果你的服务器无法识别上面POST的数据格式,那么可以尝试传统的form格式:

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

可以参考Fetch请求文档来查看所有可用的参数。

简单封装

GET

/*
     *  get请求
     *  url:请求地址
     *  params:参数
     *  callback:回调函数
     * */
    static get(url,params,callback){
        if (params) {
            let paramsArray = [];
            //拼接参数
            Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
            if (url.search(/\?/) === -1) {
                url += '?' + paramsArray.join('&')
            } else {
                url += '&' + paramsArray.join('&')
            }
        }
        //fetch请求
        fetch(url,{
            method: 'GET',
        })
            .then((response) => {
                callback(response)
            })
            .catch((error) => {
                alert(error)
            });
    }

POST

post有两种形式:

  • 第一种:’Content-Type’: ‘application/json’
/*
     *  post请求
     *  url:请求地址
     *  params:参数,这里的参数格式是:{param1: 'value1',param2: 'value2'}
     *  callback:回调函数
     * */
    static postJSON(url,params,callback){
        //fetch请求
        fetch(url,{
            method: 'POST',
            headers: {
              'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body:JSON.stringify(params)
        })
            .then((response) => response.json())
            .then((responseJSON) => {
                callback(responseJSON)
            })
            .catch((error) => {
                console.log("error = " + error)
            });
    }
  • 第二种: form表单形式
/*
     *  post请求
     *  url:请求地址
     *  params:参数,这里的参数要用这种格式:'key1=value1&key2=value2'
     *  callback:回调函数
     * */
    static postForm(url,params,callback){
        //fetch请求
        fetch(url,{
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: params
        })
            .then((response) => response.json())
            .then((responseJSON) => {
                callback(responseJSON)
            })
            .catch((error) => {
                console.log("error = " + error)
            });
    }

调用


//post请求
        let params = {'key1':'value1','key2':'value2'};
        NetRequest.postJSON('http://www.baidu.com/',params,function (set) {
            //下面的就是请求来的数据
            console.log(set)
        })

//get请求,以百度为例,没有参数,没有header
       NetRequest.get('https://www.baidu.com/','',function (set) {
            //下面是请求下来的数据
            console.log(set)
        })

解释一下:

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

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

开发交流群: 860196537

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值