typeof (res.data) == "undefined" ? "网络请求失败,请稍后再试" : res.data.desc
onFail(error)
console.log("error===========>", error);
}
},
fail: function(res) {
console.log("onFail===========>", res);
onFail("网络请求失败,稍后再试")
},
complete: function(res) {
console.log("complete===========>", isEndLoading);
if (isEndLoading){
wx.hideLoading()
}
}
})
};
三、网络环境统一切换。
在app.json中统一配置
// 全局的数据,可以提供给所有的page页面使用
globalData: {
token: "",
version: "version版本号",
releaseUrl: "正式版url",
debugUrl: "测试版url", debug: true //true debug环境,false正式环境
},这样,以后切换网络环境只需要修改debug值即可。
四、二次封装
/**
* 自定义loading 框请求
*
* isShowLoading :true 弹出loading窗
* isEndLoading: true 最后需要隐藏loading窗。若是false,则不隐藏
*/
export function request(requestData, isShowLoading = true, isEndLoading = true, onSuccess, onFail){
this.requestApi(requestData, isShowLoading, isEndLoading, null, function (result) {
onSuccess(result)
}, function (error) {
onFail(error)
})
}/**
* 带有loading 框的 不能自定义的请求
*
*/export function request1(requestData, onSuccess, onFail) { // console.log("onSuccess========request1===>", success, fail);
requestApi(requestData, true, true, null, function (result) {
onSuccess(result)
}, function (error) {
onFail(error)
})
}/**
* 自定义token 请求
*
* isShowLoading :true 弹出loading窗
* isEndLoading: true 最后需要隐藏loading窗。若是false,则不隐藏
* token: 可以自定义token。用户虚拟账号使用车辆
*/export function request2(requestData, isShowLoading = true, isEndLoading = true, token = null, onSuccess, onFail) {
requestApi(requestData, isShowLoading, isEndLoading, token, function (result) {
onSuccess(result)
}, function (error) {
onFail(error)
})
}/**
* 自定义loading 框请求
*
* isShowLoading :true 弹出loading窗
* isEndLoading: true 最后需要隐藏loading窗。若是false,则不隐藏
*/export function request3(requestData, isShowLoading = true, isEndLoading = true, token, onSuccess, onFail) {
requestApi(requestData, isShowLoading, isEndLoading, token, function (result) {
onSuccess(result)
}, function (error) {
onFail(error)
})
}end
最后,控制台查看日志的示意图为:

以上就是小程序如何实现网络请求 (详细过程)的详细内容,更多请关注php中文网其它相关文章!
小程序是一种不需要下载安装即可使用的应用,它实现了应用“触手可及”的梦想,用户扫一扫或者搜一下即可打开应用。
关键词:小程序如何完成网络请求 (详细过程)