react-native 网络请求,超时总结

前端之家收集整理的这篇文章主要介绍了react-native 网络请求,超时总结前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

react-native 网络请求总结

参考:

[1] http://www.jb51.cc/article/p-qfauherj-rd.html

[2] https://github.com/facebook/react-native/issues/2556

[3] https://github.com/robinpowered/react-native-fetch-polyfill

react-native的网络请求,总会遇到这样,或者那样的问题。这里我根据网上的资源,和自己的实践经验,总结下遇到的问题。

@H_404_13@1. 使用哪种工具请求网络?

目前react-native推荐的是fetch,XHttpRequest等工具。我自己用的fetch方法

2. 如何用fetch请求http?

http请求主流的分getpost方式. 都可以在 fetch方法中设置.

2.1 get方式请求

  1. static get(url,callback) {
  2. fetch(url)
  3. .then((response) => response.text()) .then((responseText) => { callback(JSON.parse(responseText)); }).done(); }

代码中对返回的response对象,直接调用Json.parse()方法可以解析。也可以调用response.tojson()方法

2.2 post请求

这里,我直接采用参考文章写的一个NetUtil.js工具类了,不过我们需要了解:请求时,我们可以设置响应的HTTP内容类型ContentType. 这个值,可以设置header的类型:application/json,application/x-www-form-urlencoded等(其实还有很多)。前者表示参数是json类型数据,后者表示参数是表单类型数据

  1. 'use strict';
  2. import React,{
  3. Component,} from 'react-native';
  4.  
  5. class NetUitl extends React.Component {
  6.  
  7. //post请求
  8. /** *url :请求地址 *data:参数 *callback:回调函数 */
  9. static postForm(url,data,callback) {
  10. var fetchOptions = {
  11. method: 'POST',headers: {
  12. 'Accept': 'application/json','Content-Type': 'application/x-www-form-urlencoded'
  13. },body:'data='+data+''//这里我参数只有一个data,大家可以还有更多的参数
  14. };
  15.  
  16. fetch(url,fetchOptions)
  17. .then((response) => response.json())
  18. .then((responseData) => {
  19. // 这里responseData就是一个可以用的json对象了。
  20. callback(responseData);
  21. }).catch(function(error) {
 callback(error,-1);
  22. }
  23. }
  24.  
  25. /** *url :请求地址 *data:参数(Json对象) *callback:回调函数 */
  26. static postJson (url,callback) {
  27. var fetchOptions = {
  28. method: 'POST',headers: {
  29. 'Accept': 'application/json',//json形式
  30. 'Content-Type': 'application/json'
  31. },body: JSON.stringify(data)
  32. };
  33.  
  34. fetch(url,fetchOptions)
  35. .then((response) => response.json())
  36. .then((responseData) => {
  37. // 这里responseData就是一个可以用的json对象了。
  38. callback(responseData);
  39. }).catch(function(error) {
 callback(error,-1);
  40. }
  41. }
  42. }
  43.  
  44. module.exports = NetUitl;

3. 调用方式如下:

get的调用方法

  1. NetUtil.get("http://v.juhe.cn/weather/index?format="+format+"&key="+key+"&cityname="+cityname,function (result) {
  2. // process result
  3. })

2.3 postJson的调用

  1. let data={'username':'123','password':'123456','token':'HSHSIHIFAUINNSNAFKSKJFNKFKFNFNFNK'};
  2. NetUitl.postJson(url,function (result){
  3. // process result a json object
  4. });

2.4 postForm的调用

  1. let url = Global.LOGIN;
  2. let formData = new FormData();
formData.append("id",id);
formData.append("username",username);
  3. formData.put(" NetUitl.postForm(url,sx,function (result){ // process result });

超时怎么办?

目前也没有很好的办法解决超时,看网上很多方案都不可靠,主流的方式是抛弃这次http请求。用setTimeout() 方法,抛弃这次请求。我看到另外一种,引入一个[polyfill的文件]https://github.com/robinpowered/react-native-fetch-polyfill/blob/master/fetch-polyfill.js,然后在自己的网络请求方法里,采用它定义的fetch方法,就可以设置timeout参数。亲测有效。

这是我自己的HttpUtils.js 工具类:

HttpUtils.js

  1. // 引入polyfill 解决不能设置超时的问题,直接把这个js文件拷到当前目录。
  2. // https://github.com/robinpowered/react-native-fetch-polyfill
  3.  
  4. import fetch from './fetch-polyfill';
  5.  
  6. console.warn("fetch url: " + url);
  7. getData(url,callback) {
  8. 
 fetch(url,{
  9. method: 'GET',headers: {
  10. 'Content-Type': 'application/x-www-form-urlencoded'
  11. },timeout: 20 * 1000
  12. })
  13. .then((response) => response.json()) .then((responseData) => { console.warn("response code:" + responseData.code) if(responseData.code === "C0000" || responseData.code === "1000" || responseData.code === 1000) { console.warn("response:" + responseData.data); callback(responseData.data,0); } else { callback(responseData,-1); } }).catch(error => { // an error when the request fails,such as during a timeout callback(null,-1); }); } } module.exports = { getData }

使用方法

  1. let url = getUrls() + '&id=' + id;
  2. SelfHttp.getData(url,"",(data,code) => {console.warn("get data ....11111"); if(code === 0) { // 处理data对象,取决你返回的json格式 } else { // 显示错误界面 } }

希望对你的react-native之旅有帮助。

猜你在找的React相关文章