网络编程 
首页 > 网络编程 > 浏览文章

ES6 fetch函数与后台交互实现

(编辑:jimmy 日期: 2024/5/9 浏览:3 次 )

最近在学习react-native,遇到调用后端接口的问题.看了看官方文档,推荐使用es6的fetch来与后端进行交互,在网上找了一些资料.在这里整理,方便以后查询.

1.RN官方文档中,可使用XMLHttpRequest

var request = new XMLHttpRequest();
request.onreadystatechange = (e) = >{
  if (request.readyState !== 4) {
    return;
  }
  if (request.status === 200) {
    console.log('success', request.responseText);
  } else {
    console.warn('error');
  }
};
request.open('GET', 'https://mywebsite.com/endpoint.php');
request.send();

这是http的原生方法,这里不做多的介绍.

2.RN官方文档中,推荐使用fetch

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

body中的数据就是我们需要向服务器提交的数据,比如用户名,密码等;如果上述body中的数据提交失败,那么你可能需要把数据转换成如下的表单提交的格式:

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

    console.log(res)
})

这样可以获取纯文本的返回数据.

如果你需要返回json格式的数据:

fetch('https://mywebsite.com/endpoint/').then(function(res) {

  if (res.ok) {

    res.json().then(function(obj) {

      // 这样数据就转换成json格式的了

    })

  }

}, function(ex) {
  console.log(ex)
})

fetch模拟表单提交:

fetch('doAct.action', { 

  method: 'post', 

  headers: { 

   "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" 

  }, 

  body: 'foo=bar&lorem=ipsum' 

 })

 .then(json) 

 .then(function (data) { 

  console.log('Request succeeded with JSON response', data); 

 }) 

 .catch(function (error) { 

  console.log('Request failed', error); 

 });

不过无论是ajax还是fetch,都是对http进行了一次封装,大家各取所好吧.

参考文档:https://developer.mozilla.org/zh-CN/docs/Web/API/GlobalFetch/fetch

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:element vue Array数组和Map对象的添加与删除操作
下一篇:vue-cli3全面配置详解
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网