react native 使用fetch进行网络请求(https),解决SSLHandshake问题,以及怎样进行二次封装

react native 使用fetch进行网络请求(https 问题SSLHandshake,解决办法)

  • 使用实例
  • 怎样进行封装
  • 常见问题(超时设置、无效的ssl证书、…)
  • fetch原理讲解

使用实例

1.使用get方式进行网络请求,例如:
fetch('http://nero-zou.com/test', {  
    method: 'GET'
}).then(function(response) {
   
    //获取数据,数据处理
}).catch(function(err) {
   
    //错误处理
});
2.使用post方式进行网络请求,例如:
let param = {user:'xxx',phone:'xxxxxx'};
fetch(url, {  
    method: 'post',
    body: JSON.stringify(param)
}).then(function(response) {
   
    //获取数据,数据处理
});
3.其它写法,例如:
try {
       fetch(url, {  
            method: 'post',
            body: JSON.stringify(param)
        }).then(function(response) {
   
            //获取数据,数据处理
        });  
    } catch(e) {
         //捕获异常消息    
    }
4.带header 或其它参数
fetch(url, {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  })
})

怎样进行封装

基本上要求是写个基础的函数,其它在进行网络请求时都调用这个函数。即使以后不使用fetch 直接将这个基础函数修改,不用修改其它的地方就可以实现。

基础函数的模型一般是这样的

function sendNetRequest(...props) {
   
  this.url = props.shift(1);
  this.options = props.shift(1);   
  return fetch(this.url, Object.assign({}, this.options))
  .then((response) =>return response.json());
}

封装各个接口

 //封装login 接口
 function  postLogin(userName,password) {  
    let loginParam= {user:userName,password:password};    
    var loginApiPort = "mlogin";//login 对应的接口
    //下面的baseURL=https://XXXXX.com 
    return sendNetRequest(`${baseURL}/${loginApiPort}`, {
      method: 'post',
      body: JSON.stringify(loginParam),
      headers: {
           'Content-Type
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 14
    评论
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值