最近公司使用React作为前端框架,使用了异步请求访问,这里做下总结:

React Native中虽然也内置了XMLHttpRequest 网络请求API(也就是俗称的ajax),但XMLHttpRequest 是一个设计粗糙的 API,不符合职责分离的原则,配置和调用方式非常混乱,而且基于事件的异步模型写起来也没有现代的 Promise 友好。而Fetch 的出现就是为了解决 XHR 的问题,所以react Native官方推荐使用Fetch API。

fetch请求示例如下:

return fetch('http://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});

Fetch API的详细介绍及使用说明请参考如下文章:

使用Promise封装fetch请求

由于在项目中很多地方都需要用到网络请求,为了使用上的方便,使用ES6的Promise来封装fetch网络请求,代码如下:

let common_url = 'http://192.168.1.1:8080/';  //服务器地址
let token = '';
/**
* @param {string} url 接口地址
* @param {string} method 请求方法:GET、POST,只能大写
* @param {JSON} [params=''] body的请求参数,默认为空
* @return 返回Promise
*/
function fetchRequest(url, method, params = ''){
let header = {
"Content-Type": "application/json;charset=UTF-8",
"accesstoken":token //用户登陆后返回的token,某些涉及用户数据的接口需要在header中加上token
};
console.log('request url:',url,params); //打印请求参数
if(params == ''){ //如果网络请求中没有参数
return new Promise(function (resolve, reject) {
fetch(common_url + url, {
method: method,
headers: header
}).then((response) => response.json())
.then((responseData) => {
console.log('res:',url,responseData); //网络请求成功返回的数据
resolve(responseData);
})
.catch( (err) => {
console.log('err:',url, err); //网络请求失败返回的数据
reject(err);
});
});
}else{ //如果网络请求中带有参数
return new Promise(function (resolve, reject) {
fetch(common_url + url, {
method: method,
headers: header,
body:JSON.stringify(params) //body参数,通常需要转换成字符串后服务器才能解析
}).then((response) => response.json())
.then((responseData) => {
console.log('res:',url, responseData); //网络请求成功返回的数据
resolve(responseData);
})
.catch( (err) => {
console.log('err:',url, err); //网络请求失败返回的数据
reject(err);
});
});
}
}

使用fetch请求,如果服务器返回的中文出现了乱码,则可以在服务器端设置如下代码解决: 
produces="text/html;charset=UTF-8"

fetchRequest使用如下:

  • GET请求:
fetchRequest('app/book','GET')
.then( res=>{
//请求成功
if(res.header.statusCode == 'success'){
//这里设定服务器返回的header中statusCode为success时数据返回成功 }else{
//服务器返回异常,设定服务器返回的异常信息保存在 header.msgArray[0].desc
console.log(res.header.msgArray[0].desc);
}
}).catch( err=>{
//请求失败
})
  • POST请求:
let params = {
username:'admin',
password:'123456'
}
fetchRequest('app/signin','POST',params)
.then( res=>{
//请求成功
if(res.header.statusCode == 'success'){
//这里设定服务器返回的header中statusCode为success时数据返回成功 }else{
//服务器返回异常,设定服务器返回的异常信息保存在 header.msgArray[0].desc
console.log(res.header.msgArray[0].desc);
}
}).catch( err=>{
//请求失败
})

fetch超时处理

由于原生的Fetch API 并不支持timeout属性,如果项目中需要控制fetch请求的超时时间,可以对fetch请求进一步封装实现timeout功能,代码如下:

fetchRequest超时处理封装

/**
* 让fetch也可以timeout
* timeout不是请求连接超时的含义,它表示请求的response时间,包括请求的连接、服务器处理及服务器响应回来的时间
* fetch的timeout即使超时发生了,本次请求也不会被abort丢弃掉,它在后台仍然会发送到服务器端,只是本次请求的响应内容被丢弃而已
* @param {Promise} fetch_promise fetch请求返回的Promise
* @param {number} [timeout=10000] 单位:毫秒,这里设置默认超时时间为10秒
* @return 返回Promise
*/
function timeout_fetch(fetch_promise,timeout = 10000) {
let timeout_fn = null; //这是一个可以被reject的promise
let timeout_promise = new Promise(function(resolve, reject) {
timeout_fn = function() {
reject('timeout promise');
};
}); //这里使用Promise.race,以最快 resolve 或 reject 的结果来传入后续绑定的回调
let abortable_promise = Promise.race([
fetch_promise,
timeout_promise
]); setTimeout(function() {
timeout_fn();
}, timeout); return abortable_promise ;
} let common_url = 'http://192.168.1.1:8080/'; //服务器地址
let token = '';
/**
* @param {string} url 接口地址
* @param {string} method 请求方法:GET、POST,只能大写
* @param {JSON} [params=''] body的请求参数,默认为空
* @return 返回Promise
*/
function fetchRequest(url, method, params = ''){
let header = {
"Content-Type": "application/json;charset=UTF-8",
"accesstoken":token //用户登陆后返回的token,某些涉及用户数据的接口需要在header中加上token
};
console.log('request url:',url,params); //打印请求参数
if(params == ''){ //如果网络请求中没有参数
return new Promise(function (resolve, reject) {
timeout_fetch(fetch(common_url + url, {
method: method,
headers: header
})).then((response) => response.json())
.then((responseData) => {
console.log('res:',url,responseData); //网络请求成功返回的数据
resolve(responseData);
})
.catch( (err) => {
console.log('err:',url, err); //网络请求失败返回的数据
reject(err);
});
});
}else{ //如果网络请求中带有参数
return new Promise(function (resolve, reject) {
timeout_fetch(fetch(common_url + url, {
method: method,
headers: header,
body:JSON.stringify(params) //body参数,通常需要转换成字符串后服务器才能解析
})).then((response) => response.json())
.then((responseData) => {
console.log('res:',url, responseData); //网络请求成功返回的数据
resolve(responseData);
})
.catch( (err) => {
console.log('err:',url, err); //网络请求失败返回的数据
reject(err);
});
});
}
}

加入超时处理的fetchRequest网络请求的使用方法跟没加入超时处理一样。 
对于fetch网络请求的超时处理的封装参考下面这篇文章而写:

让fetch也可以timeout

引用原文:http://blog.csdn.net/withings/article/details/71331726

写博客是为了记住自己容易忘记的东西,另外也是对自己工作的总结,文章可以转载,无需版权。希望尽自己的努力,做到更好,大家一起努力进步!

如果有什么问题,欢迎大家一起探讨,代码如有问题,欢迎各位大神指正!

React Native 网络请求封装:使用Promise封装fetch请求的更多相关文章

  1. 《React Native 精解与实战》书籍连载「React Native 网络请求与列表绑定」

    此文是我的出版书籍<React Native 精解与实战>连载分享,此书由机械工业出版社出版,书中详解了 React Native 框架底层原理.React Native 组件布局.组件与 ...

  2. react native 网络get请求方式参数不可为undefined或null

    react native 网络get请求方式参数不可为undefined(为空的话默认变为)或null 错误写法: export function addToCartAction(isRefreshi ...

  3. React Native网络请求

    很多移动应用都需要从远程地址中获取数据或资源.你可能需要给某个REST API发起POST请求以提交用户数据,又或者可能仅仅需要从某个服务器上获取一些静态内容--以下就是你会用到的东西.新手可以对照这 ...

  4. React Native网络编程之Fetch

    目录 1.前言 2.什么是Fetch 3.最简单的应用 4.支持的请求参数 - 4.1. 参数详讲 - 4.2. 示例 5.请求错误与异常处理   1. 前言   网络请求是开发APP中不可或缺的一部 ...

  5. React Native 网络请求

    如下面的Code,分别介绍了GET,POST,以及使用XMLHttpRequest的Get请求. import React, { Component } from 'react'; import { ...

  6. vue axios接口封装、Promise封装、简单的axios方法封装、vue接口方法封装、vue post、get、patch、put方法封装

    相信大家在做前后端数据交互的时候都会给请求做一些简单的封装就像之前封装ajax方法一样axios的封装也是一样的简单下面这个就是封装的axios的方法,require.js import axios ...

  7. React Native之Fetch简单封装、获取网络状态

    1.Fetch的使用 fetch的使用非常简单,只需传入请求的url fetch('https://facebook.github.io/react-native/movies.json'); 当然是 ...

  8. [React Native]Promise机制

    React Native中经常会看到Promise机制. Promise机制代表着在JavaScript程序中下一个伟大的范式.可以把一些复杂的代码轻松撸成一个串,和Android中的rxjava非常 ...

  9. react native中如何往服务器上传网络图片

    let common_url = 'http://192.168.1.1:8080/'; //服务器地址 let token = ''; //用户登陆后返回的token /** * 使用fetch实现 ...

随机推荐

  1. 基础-Eclipse 教程

    1.Eclipse 是一个开放源代码的.基于 Java 的可扩展开发平台.2.下载地址为: https://www.eclipse.org/downloads/.3.Eclipse 修改字符集 : W ...

  2. HDU 5321 Beautiful Set

    题目链接 我们能够枚举子集的大小k.求出全部大小为k的子集对答案的贡献.问题就攻克了. 注意到欧拉函数的性质:n=∑φ(d),d|n 莫比乌斯函数性质:∑d|nμ(d)=0n>1 感谢http: ...

  3. 3162 抄书问题(划分dp)

    3162 抄书问题 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 钻石 Diamond 题解 查看运行结果 题目描述 Description 现在要把M本有顺序的书分给K个人复制( ...

  4. Linux增加swap分区的方法

    在装完Linux系统之后,建立Swap分区有两种方法. 1.新建磁盘分区作为swap分区2.用文件作为swap分区 (操作更简单,我更常用) 一.新建磁盘分区作为swap分区 1. # swapoff ...

  5. 讨论cocos2d-x字体绘制原理和应用方案

    转自:http://blog.csdn.net/langresser_king/article/details/9012789 个人一直认为,文字绘制是cocos2d-x最薄弱的环节.对于愤怒的小鸟之 ...

  6. Linux下修改Mysql的用(root的密码及修改root登录权限

    修改的用户都以root为列. 一.知道原来的myql数据库的root密码: ①: 在终端命令行输入 mysqladmin -u root -p password "新密码" 回车  ...

  7. Button 自动换行

    UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 200, self.view.frame.size.width, 300)]; view ...

  8. git "Could not read from remote repository.Please make&n

    git "Could not read from remote repository.Please make sure you have the correct access rights. ...

  9. Android ViewGroup onInterceptTouchEvent

    public boolean onInterceptTouchEvent (MotionEvent ev) Implement this method to intercept all touch s ...

  10. tomcat 日志目录 介绍

    [root@mysql tomcat]# ll 总用量 drwxr-x---. root root 11月 : bin -rw-r-----. root root 11月 : BUILDING.txt ...