前言 小程序开发,没有vue中的axios那么好使,请求层的封装需要自己来搞。

当然请求层的配置少不了loading,这里索性也就将loading做一个配置,避免以后重复造轮子

请求封装

小程序中有封装好的请求方法:wx.request(url,method,header,success,fail,complete);方法类似于原生的ajax,

这里我们大的方面分两种,一种普通请求,一种是文件上传

普通请求又分为get请求,post请求,post请求又分为JSON格式和BODY格式因此

我们需要大致分为两步

普通请求

封装get请求和post请求为普通请求,我们需要考虑因为其post请求有两种方式所以我们需要将其作为参数来使。

// get/post请求
function fun(url, method, data, header) {
data = data || {};
header = header || {};
wx.showNavigationBarLoading();
let promise = new Promise(function (resolve, reject) {
wx.request({
url: baseUrl + url,
header: header,
data: data,
method: method,
success: function (res) {
if (typeof res.data === "object") {
if (res.data.status) {
if (res.data.status === -200) {
wx.showToast({
title: "为确保能向您提供最准确的服务,请退出应用重新授权",
icon: "none"
});
reject("请重新登录");
} else if (res.data.status === -201) {
wx.showToast({
title: res.data.msg,
icon: "none"
});
setTimeout(function () {
wx.navigateTo({
url: "/pages/user/supplement/supplement"
});
}, 1000);
reject(res.data.msg);
}
}
}
resolve(res.data.result);
},
fail: function (res) {
// fail调用接口失败
reject({ error: '网络错误', code: 0 });
},
complete: function () {
wx.hideNavigationBarLoading();
}
});
});
return promise;
}

文件上传

upload上传和请求方法十分类似,不过不同的是请求是request上传则是upload方法。这里上传采用小程序原生的方法

function upload(url, name, filePath) {
let header = {};
wx.showNavigationBarLoading();
let promise = new Promise(function (resolve, reject) {
wx.uploadFile({
url: baseUrl + url,
filePath: filePath,
name: name,
header: header,
success: function (res) {
resolve(res.data.result);
},
fail: function() {
reject({ error: '网络错误', code: 0 });
},
complete: function () {
wx.hideNavigationBarLoading();
}
});
});
return promise;
}

我们只需要导出以上两种方法即可,不过认真看过的同学会发现baseUrl没有定义啊

这里童鞋们可以根据实际情况,分为开发,测试,生产,生产测试等情况分类,设置baseUr基本域名

这里就不做说明了。

下来我们就是最后一步了,这一步不影响使用。但是为了完美~beautiful

配置loading让交互会更加的友好

配置loading,我们不需要封装loading框,调用小程序自带的就可以,我们只需要操心的是,一个页面很多请求的时候,如何当所有请求完成时再关闭loading?

实现思路:设置一个计数器,因为这里的请求方法都要经过fun,所以说我们只需要在fun调用的时候+1,在返回失败或者成功的时候-1就可以,当等于0的时候调用关闭loading的方法就可以了,笔者简直不要太完美~

// loading配置,请求次数统计
function startLoading() {
wx.showLoading({
title: 'Loading...',
icon: 'none'
})
}
function endLoading() {
wx.hideLoading();
}
// 声明一个对象用于存储请求个数
var needLoadingRequestCount = 0;
function showFullScreenLoading() {
if (needLoadingRequestCount === 0) {
startLoading();
}
needLoadingRequestCount++;
};
function tryHideFullScreenLoading() {
if (needLoadingRequestCount <= 0) return;
needLoadingRequestCount--;
if (needLoadingRequestCount === 0) {
endLoading();
}
};

我们只需要在fun方法中添加showFullScreenLoading(),在返回结果的时候调用tryHideFullScreenLoading()即可实现请求层封装与loading的全局配置~完美不?

源码

下来将源码附上,有帮助的话,记得点个关注呗,待个人网站完善后将会同步至个人网站(百度搜索:狗尾草的前端博客)

const app = getApp()

const baseUrl = app.globalData.baseUrl;

// loading配置,请求次数统计
function startLoading() {
wx.showLoading({
title: 'Loading...',
icon: 'none'
})
}
function endLoading() {
wx.hideLoading();
}
// 声明一个对象用于存储请求个数
var needLoadingRequestCount = 0;
function showFullScreenLoading() {
if (needLoadingRequestCount === 0) {
startLoading();
}
needLoadingRequestCount++;
};
function tryHideFullScreenLoading() {
if (needLoadingRequestCount <= 0) return;
needLoadingRequestCount--;
if (needLoadingRequestCount === 0) {
endLoading();
}
}; // get/post请求
function fun(url, method, data, header) {
data = data || {};
header = header || {};
wx.showNavigationBarLoading();
showFullScreenLoading();
let promise = new Promise(function (resolve, reject) {
wx.request({
url: baseUrl + url,
header: header,
data: data,
method: method,
success: function (res) {
if (typeof res.data === "object") {
if (res.data.status) {
if (res.data.status === -200) {
wx.showToast({
title: "为确保能向您提供最准确的服务,请退出应用重新授权",
icon: "none"
});
reject("请重新登录");
} else if (res.data.status === -201) {
wx.showToast({
title: res.data.msg,
icon: "none"
});
setTimeout(function () {
wx.navigateTo({
url: "/pages/user/supplement/supplement"
});
}, 1000);
reject(res.data.msg);
}
}
}
resolve(res.data.result);
tryHideFullScreenLoading();
},
fail: function (res) {
// fail调用接口失败
reject({ error: '网络错误', code: 0 });
tryHideFullScreenLoading();
},
complete: function () {
wx.hideNavigationBarLoading();
}
});
});
return promise;
} // 上传
function upload(url, name, filePath) {
let header = {};
wx.showNavigationBarLoading();
showFullScreenLoading();
let promise = new Promise(function (resolve, reject) {
wx.uploadFile({
url: baseUrl + url,
filePath: filePath,
name: name,
header: header,
success: function (res) {
resolve(res.data.result);
tryHideFullScreenLoading();
},
fail: function() {
reject({ error: '网络错误', code: 0 });
tryHideFullScreenLoading();
},
complete: function () {
wx.hideNavigationBarLoading();
wx.hideLoading();
}
});
});
return promise;
} module.exports = {
"get": function (url, data, header) {
return fun(url, "GET", data, header);
},
"post": function (url, data, header) {
return fun(url, "POST", data, header);
},
upload: function (url, name, filePath) {
return upload(url, name, filePath);
}
};

使用说明,需要在调用方法的时候传入header,为json格式的还是body格式,总结不易,你的关注是我更新的吃鸡动力~

小程序api请求层封装(Loading全局配置)的更多相关文章

  1. 微信小程序request请求的封装

    目录 1,前言 2,实现思路 3,实现过程 3.1,request的封装 3.2,api的封装 4,实际使用 1,前言 在开发微信小程序的过程中,避免不了和服务端请求数据,微信小程序给我们提供了wx. ...

  2. 基于promise对小程序http请求方法封装

    原因是我不想每次请求都复制粘贴那么长的请求地址,所以我把前边那一坨请求地址作为基础地址,只传后台给的路由就ok,而且,并不是每次请求都要显示正在加载,这对小程序体验很差,所以,我加了个形参,用来判断是 ...

  3. 小程序api的promise封装

    微信小程序和支付宝小程序的api封装方法是一样的,都是外部新建一个js,使用module.exports导出,要注意的是,最好使用post请求,虽然get请求没什么不好,主要是好修改.这里使用的MD5 ...

  4. 微信小程序 之 请求函数封装

    封装的request的代码 /** * @desc API请求接口类封装 */ /** * POST请求API * @param {String} url 接口地址 * @param {Object} ...

  5. 小程序-API请求

    Page({ onLoad:function(){ // 在onLoad中调用发送请求的函数 this.getProList(); } getProList:function(){ var self= ...

  6. mpvue学习笔记-之微信小程序数据请求封装

    简介 美团出品的mpvue已经开源出来很久了,一直说要进行一次实践,这不最近一次个人小程序开发就用上了它. 看了微信官方的数据请求模块--request,对比了下get和post请求的代码,发现如果在 ...

  7. 微信小程序开发——使用promise封装异步请求

    前言: 有在学vue的网友问如何封装网络请求,这里以正在写的小程序为例,做一个小程序的请求封装. 关于小程序发起 HTTPS 网络请求的Api,详情可以参考官方文档:wx.request(Object ...

  8. 微信小程序开发——连续快速点击按钮调用小程序api返回后仍然自动重新调用的异常处理

    前言: 小程序开发中诸如获取用户手机号码.调起微信支付.领取卡券等api都是会有一定的延迟的.也就是说通过点击按钮调用这些api的时候,从点击按钮调用api,到支付页面或者领取卡券界面展示出来是需要一 ...

  9. 微信小程序(二)--逻辑层与界面层

    一.逻辑层与界面层分离 小程序开发框架将我们需要完成的编码,划分成了两种类型的编码:逻辑编码(由JavaScript完成,业务数据供给界面事件处理),界面编码(页面结构WXML,页面样式WXSS,展示 ...

随机推荐

  1. 深度学习框架Keras安装

    环境:Windows 10 64位 版本!版本!版本!不要下载最新版本的! 一点要按照这个来!安装顺序也最好不要错! 首先安装DirectX SDK工具包 ,这是链接:https://www.micr ...

  2. python3.6 ImportWarning: can't resolve package from __spec__ or __package__, falling back on __name__ and __path__

    Cython emulates Python 2-style implicit relative imports on Python 3 Cython的锅(也就是绝大多数下载安装的python)新的i ...

  3. hdu 5724-Chess(状态压缩+sg函数)

    hdu 5724-Chess 代码: #include<bits/stdc++.h> using namespace std; ; <<N]; bool S[N]; void ...

  4. SQLSERVER 对于非dbo的表增加注释

    平时我们创建表的时候总是dbo.imsi_collect_state,但是有时候为了方便管理我们可能会创建架构wifi,那么表名就是wifi.imsi_collect_state 原来增加注释的方式是 ...

  5. linux机器之间拷贝和同步文件命令

    1 不同机器拷贝文件 scp 文件     登录用户@机器IP:/目录/子目录 scp filename test@10.20.130.202:/home/test/ 2 文件[夹]同步 rsync ...

  6. php file_get_contents计时读取一个文件/页面 防止读取不到内容

    php file_get_contents计时读取一个文件/页面 防止读取不到内容 $url = 'http://www.baidu.com/index.php'; $opts = array( 'h ...

  7. WPF几种高级绑定

    (1)Binding  + RelativeSource + AncestorType 模式  , 根据关联源所指定的类型,可动态绑定指定类型的Path属性(Path可以省略)(PS:动态指父级在运行 ...

  8. windows下apache利用SSL来配置https

    第一步打开httpd.conf文件找到以下两个变量把注释去掉. #LoadModule ssl_module modules/mod_ssl.so (去掉前面的#号) #Include conf/ex ...

  9. 『cs231n』作业1选讲_通过代码理解KNN&交叉验证&SVM

    通过K近邻算法探究numpy向量运算提速 茴香豆的“茴”字有... ... 使用三种计算图片距离的方式实现K近邻算法: 1.最为基础的双循环 2.利用numpy的broadca机制实现单循环 3.利用 ...

  10. springmvc事务回滚失效

    转载:http://blog.csdn.net/z69183787/article/details/37819831 前文提到,最新换了框架,新项目用SpringMVC + Spring JdbcTe ...