// 1: 传统fetch操作
fetch('http://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
//操作
})
.catch((error) => {
console.error(error);
});// 2:使用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);
});
});
}
}
// 然后我们去使用这个封装请求函数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=>{
//请求失败
})// 3:加入超时处理,跟上面没关系
/**
* 让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 的结果来传入后续绑定的回调,
//先执行fetch_promise 等待数据的返回,如果在定时后还没返回 就执行超时函数
let abortable_promise = Promise.race([
fetch_promise,
timeout_promise
]);setTimeout(function() {
timeout_fn();
}, timeout);return abortable_promise ;
}//应用:加入超时处理的fetchRequest网络请求的使用方法跟没加入超时处理一样。
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);
});
});
}
}
//参考文章http://imweb.io/topic/57c6ea35808fd2fb204eef63

转载于:https://www.cnblogs.com/allenxieyusheng/p/7656677.html

封装fetch的使用(包含超时处理)相关推荐

  1. 【Java代码】京东商品全部分类数据获取(建表语句+Jar包依赖+树结构封装+爬虫源代码)包含csv和sql格式数据下载可用

    [资源链接] 链接:https://pan.baidu.com/s/15fuerPIQgmwV1MZEts8jEQ 提取码:6psl [包含文件] 1.说明 当前项目需要用到商品分类数据,在网上查了淘 ...

  2. 封装fetch请求方法

    /*** 加载中ing* @returns*/ function showLoading() {$('body').loading({loadingWidth:120,title:'',name:'l ...

  3. fetch设置请求超时

    常规封装 fetch // 封装fetch let POST = function(url, params) {const URLS = baseURL + url;return fetch(URLS ...

  4. React Native Fetch封装那点事...

    每一门语言都离不开网络请求,有自己的一套Networking Api.React Native使用的是Fetch. 今天我们来谈谈与Fetch相关的一些事情. purpose 通过这篇文章,你将了解到 ...

  5. 文件包含漏洞特点和php封装伪协议

    渗透学习 文件包含漏洞 文章目录 渗透学习 前言 *本文只做学习用途,严禁利用本文提到的技术进行非法攻击,否则后果自负,本人不承担任何责任.* 一.文件包含漏洞 二.实验步骤 1.文件包含特点 2.本 ...

  6. js ES6 fetch 方法

    目录 一.fetch 概述 二.fetch 的语法 1.实现一个简单的 fetch 请求 2.fetch 方法介绍 (1).fetch 方法的第一个参数 (2).fetch 方法的第二个参数 (3). ...

  7. 浅谈xhr和fetch

    浅谈xhr和fetch 什么是xhr 使用 fetch 使用 在两者没封装前的区别 什么是xhr xhr就是是XMLHttpRequest,是浏览器内置的api,可以和服务端进行交互,获取数据无需要页 ...

  8. React (fetch redux初识 state action reducer getState dispatch .subscribe 取消监听 ActionTypes Action Crea)

    axios数据交互 安装axios cnpm i axios --save 2.发起http请求 this.axios.get('/api/menulist').then(res=>{conso ...

  9. 史上最全的 axios 工具封装

    npm使用国内淘宝镜像的方法 npm install -g cnpm --registry=https://registry.npm.taobao.org npm 导入axios 包 cnpm ins ...

最新文章

  1. 小程序“errcode“:41002错误问题如何解决?
  2. java 抽象类继承抽象类_Java之继承、抽象类、接口篇
  3. 腾讯旗下网站的很多URL都包含“cgi-bin”,是什么意思?他们后台用什么语言?...
  4. Git之Stash(储藏)备份当前的工作区的内容
  5. 简易电子钟c语言程序,(最新整理)基于51单片机的电子钟C语言程序
  6. 公众号jdk 获取手机号_怎样快速获取使用国庆节公众号文章的素材和模板
  7. 绘制北京市蜜雪冰城门店地图
  8. taptap需要相机权限_TapTap双击背部App-实现安卓11双击手机背面截屏拍照等新功能-软极客...
  9. 大话西游2服务器维护公告,2017年02月23日停机维护公告
  10. mingw32 编译 fastdb
  11. HoneyFramework蜂巢框架六边形生成unity地图使用教程提示和技巧
  12. 20_java使用谷歌邮箱发送邮件
  13. 爱了爱了,这样的文字动画让你爱不释手
  14. Lesson 57 An unusual day 很不平常的一天
  15. 视频剪辑软件如何合并分割视频文件
  16. C++第8周项目3小贺的工资
  17. 当当电子书生成pdf示例
  18. 侠盗猎车手:圣安地列斯》GTA SA 作弊码 转
  19. 解析EDA系统集成方案设计
  20. Android OpenGl学习(一)

热门文章

  1. linux内核自旋锁API
  2. 使用secureCRT连接VMware-Ubuntukylin虚拟机
  3. 转[WinForm] VS2010发布、打包安装程序(超全超详细)
  4. 快速安装本地yum源
  5. Json解析异常处理方式(JSONException: Value of type java.lang.String cannot be converted to JSONObject)...
  6. 解决不是有效的win32应用程序
  7. DNS 与 活动目录 的关系
  8. 自动发现网络拓扑,一站式点击完成
  9. ASP.NetViewState的实现方案
  10. 【Python-ML】神经网络-Theano张量库(GPU版的Numpy)