api.js
const host = "https://www.baidu.com/wx/api";
const api = {
host: host,
apiWxLogin: `${host}/Auth/WxLoginV2`,
apiHome: `${host}/home/index`,
apiGetCartCount: `${host}/Cart/CartNum`,
getCartCount() {
this.http({
api: 'apiGetCartCount',
loading: false,
success: res => {
if (res.CartNum > 0) {
wx.setTabBarBadge({
index: 3,
text: '' + res.CartNum
});
} else {
wx.removeTabBarBadge({
index: 3
});
}
}
})
},
toast: function (msg) {
wx.showToast({
icon: 'none',
title: msg,
duration: msg.length > 10 ? 2500 : 1500
});
},
http: function (option) {
const config = {
api: '',
data: {},
success: null,
error: null,
notlogin: null,
loading: true,
}
for (let key in option) {
config[key] = option[key];
}
let url = "";
if (config.api) {
url = this[config.api] || "";
}
if (!url) {
return;
}
if (config.loading) {
wx.showLoading({
title: config.loading === true ? "加载中" : config.loading
});
}
wx.request({
url: url,
data: config.data,
method: "POST",
header: {
huaSessionId: wx.getStorageSync("wxUserInfoKey"),
version: version
},
success(response) {
if (config.loading) {
wx.hideLoading();
}
const res = response.data;
if (res.Status === "0") {
if (res.DataStatus === 200) {
if (config.success) {
config.success(res.Datas);
}
} else if (res.DataStatus === 1500) {
} else if (res.DataStatus === 1501) {
api.toast("授权信息已失效,请重新授权~");
wx.redirectTo({
url: "/pages/login/index"
});
} else if (res.DataStatus === 1502) {
wx.navigateTo({
url: "/pages/login/loginbind/index"
});
} else {
if (config.error) {
config.error(res);
} else {
const datas = res.Datas == null ? {} : res.Datas;
api.toast(res.ErrMsg || datas.Message || "网络错误,请稍后再试(1)~");
}
}
} else {
if (config.error) {
config.error(res);
} else {
const datas = res.Datas == null ? {} : res.Datas;
api.toast(res.ErrMsg || datas.Message || "网络错误,请稍后再试(2)~");
}
}
},
fail: function (err) {
api.toast("网络错误,请稍后再试~");
if (config.error) {
config.error(err);
}
},
})
},
};
module.exports = api;
page.js
const api = require("../../utils/api.js");
api.http({
api:"apiHome",
data:{},
success:res => {
console.log("success!")
},
error:err => {
console.log("error!")
},
loading:false
})