1. 未封装前index.vue页面使用
getMachineNum:function(){
var timestamp = Date.parse(new Date());//时间戳
var token = uni.getStorageSync(_self.sessionKey);
var device = "wxapp";
var ver = "1.1.30";
uni.request({
url: this.siteBaseUrl + 'machine/index',
method: 'GET',
data: {
token : token,
timestamp : timestamp,
device : device,
ver : ver
},
success: res => {
console.log("getMachineNum success:" + JSON.stringify(res));
if (res.data.code == "-1") {//登录失效
uni.showToast({
title: res.data.msg,
mask: false,
duration: 1500
});
} else if (res.data.code == "0") {
var data = res.data.data;
_self.onlineNum = data.onlineNum;
_self.machineNum = data.machineNum;
}else {
console.log("未处理的结果码");
}
},
fail: (e) => {
console.log("getMachineNum fail:" + JSON.stringify(e));
},
complete: () => {}
});
},
请求结果
{
"data": {
"code": "0",
"msg": "success",
"data": {
"machineNum": 124,
"onlineNum": 1,
}
},
"header": {
"Server": "nginx/1.14.0",
"Date": "Thu, 11 Apr 2019 03:08:20 GMT",
"Content-Type": "application/json;charset=utf-8;",
"Transfer-Encoding": "chunked",
"Connection": "keep-alive",
"X-Powered-By": "PHP/7.1.16"
},
"statusCode": 200,
"cookies": [],
"errMsg": "request:ok"
}
2. main.js中封装网络请求
Vue.prototype.sendRequest= function(param,backpage, backtype){
var _self = this,
url = param.url,
data = param.data || {},
header = param.header,
token = "";
//拼接完整请求地址
var requestUrl = this.siteBaseUrl + url;
//固定参数
if(!data.token){//如果参数中无token(除了小程序第一次通过code获取token的接口默认参数token = login,其他接口token参数都是在本地缓存中获取)
token = uni.getStorageSync(this.sessionKey);
if(!token){//本地无token需重新登录
_self.login(backpage, backtype);
return;
}else{
data.token = token;
}
}
var timestamp = Date.parse(new Date());//时间戳
data["timestamp"] = timestamp;
data["device"] = "wxapp";//data["device"] = "iosapp";
data["ver"] = "1.1.30";//data["ver"] = "1.0.0";
//GET或POST
if(param.method){
param.method = param.method.toUpperCase();//小写改为大写
}
//网络请求
uni.request({
url: requestUrl,
method: param.method || "GET",
header: header || {'content-type' : "application/json"},
data: data,
success: res => {
console.log("网络请求success:" + JSON.stringify(res));
if (res.statusCode && res.statusCode != 200) {//api错误
uni.showModal({
content:"" + res.errMsg
});
return;
}
if (res.data.code) {//返回结果码code判断:0成功,1错误,-1未登录
if (res.data.code == "-1") {
_self.login(backpage, backtype);
return;
}
if (res.data.code != "0") {
uni.showModal({
showCancel:false,
content:"" + res.data.msg
});
return;
}
} else{
uni.showModal({
showCancel:false,
content:"" + res.data.msg
});
return;
}
typeof param.success == "function" && param.success(res.data);
},
fail: (e) => {
console.log("网络请求fail:" + JSON.stringify(e));
uni.showModal({
content:"" + res.errMsg
});
typeof param.fail == "function" && param.fail(res.data);
},
complete: () => {
console.log("网络请求complete");
uni.hideLoading();
typeof param.complete == "function" && param.complete(res.data);
return;
}
});
}
Vue.prototype.login = function(backpage, backtype){
var _self = this;
uni.login({
success:function(res){
_self.requestData({
url : "user/login",
data : {
code : res.code,
token : "login"
},
success : function(res2){
if (res2.data.errCode == "0") {//用户存在:存储token
uni.setStorageSync(_self.sessionKey,res2.data.token);
} else if (res2.data.errCode == "0") {//用户不存在:调转到绑定页面
uni.redirectTo({url:'../binding/binding?backpage='+backpage+'&backtype='+backtype});
return false;
}
}
},backpage, backtype)
},
fail:function(e){
console.log("微信login接口调用失败:" + JSON.stringify(e));
}
});
return;
}
Vue.prototype.siteBaseUrl = 'https://api.uchat.com.cn/';
Vue.prototype.sessionKey = "sess_jk";
3. 封装后index.vue页面get请求调用
getMachineNum:function(){
this.sendRequest({
url : "machine/index",
success : function(res){
console.log("getMachineNum success:" + JSON.stringify(res));
var data = res.data;
_self.onlineNum = data.onlineNum || 0;
_self.machineNum = data.machineNum || 0;
},
fail:function(e){
console.log("getMachineNum fail:" + JSON.stringify(e));
}
},'../myhome/myhome','2')
}
注意
:页面POST请求header需配置为 {'content-type' : "application/x-www-form-urlencoded"},如:
initData:function () {
this.sendRequest({
url : "CompanyTeam/teamInfo",
data : {ct_id : ct_id},
method : "POST",
header: {'content-type' : "application/x-www-form-urlencoded"},
success:function (res) {
console.log("获取数据:" + JSON.stringify(res));
}
},"/pages/machineGroupOutput/machineGroupOutput","1")
},
故,可对网络请求封装继续优化。
4. 网络请求封装优化
Vue.prototype.sendRequest = function(param,backpage, backtype){
var _self = this,
url = param.url,
method = param.method,
header = {},
data = param.data || {},
token = "";
//拼接完整请求地址
var requestUrl = this.siteBaseUrl + url;
//固定参数:仅仅在小程序绑定页面通过code获取token的接口默认传递了参数token = login
if(!data.token){//其他业务接口传递过来的参数中无token
token = uni.getStorageSync(this.sessionKey);//参数中无token时在本地缓存中获取
console.log("当前token:" + token);
if(!token){//本地无token需重新登录(退出时清缓存token)
_self.login(backpage, backtype);
return;
}else{
data.token = token;
}
}
var timestamp = Date.parse(new Date());//时间戳
data["timestamp"] = timestamp;
// #ifdef MP-WEIXIN
data["device"] = "wxapp";
data["ver"] = "1.1.30";
// #endif
// #ifdef APP-PLUS || H5
data["device"] = "iosapp";
data["ver"] = "1.0.0";
// #endif
//请求方式:GET或POST(POST需配置header: {'content-type' : "application/x-www-form-urlencoded"},)
if(method){
method = method.toUpperCase();//小写改为大写
if(method=="POST"){
header = {'content-type' : "application/x-www-form-urlencoded"};
}else{
header = {'content-type' : "application/json"};
}
}else{
method = "GET";
header = {'content-type' : "application/json"};
}
//用户交互:加载圈
if (!param.hideLoading) {
uni.showLoading({title:'加载中...'});
}
console.log("网络请求start");
//网络请求
uni.request({
url: requestUrl,
method: method,
header: header,
data: data,
success: res => {
console.log("网络请求success:" + JSON.stringify(res));
if (res.statusCode && res.statusCode != 200) {//api错误
uni.showModal({
content:"" + res.errMsg
});
return;
}
if (res.data.code) {//返回结果码code判断:0成功,1错误,-1未登录(未绑定/失效/被解绑)
if (res.data.code == "-1") {
_self.login(backpage, backtype);
return;
}
if (res.data.code != "0") {
uni.showModal({
showCancel:false,
content:"" + res.data.msg
});
return;
}
} else{
uni.showModal({
showCancel:false,
content:"No ResultCode:" + res.data.msg
});
return;
}
typeof param.success == "function" && param.success(res.data);
},
fail: (e) => {
console.log("网络请求fail:" + JSON.stringify(e));
uni.showModal({
content:"" + e.errMsg
});
typeof param.fail == "function" && param.fail(e.data);
},
complete: () => {
console.log("网络请求complete");
uni.hideLoading();
typeof param.complete == "function" && param.complete();
return;
}
});
}
页面POST请求调用
initData:function () {
this.sendRequest({
url : "CompanyTeam/teamInfo",
data : {ct_id : ct_id},
method : "POST",
success:function (res) {
console.log("获取数据:" + JSON.stringify(res));
}
},"/pages/machineGroupOutput/machineGroupOutput","1")
},
拓展:设置网络请求为同步可参考Promise 封装。大致可分为三种方案:请求嵌套(异步方式的成功回调里获取数据后再采用异步方式请求)、promise 或者await,具体实现可自行实践,这里不详细叙述。