- require.js
/**
* 网络请求公共方法:
* 1.基本的请求
* 2.为了后续,promise处理 :fetch
* 3.对数据的状态处理 lodding toast
* 4.请求头处理 !!!机型 大小 系统 屏幕
*/
const store = require('../utils/store.js');
const Animation=require('../utils/animation.js')
const system = store.getSystemInfo();
const clientInfo = {
"clientType": "mp",
"appnm": "facility-access-miniprogram",
"model": system.model,
"os": system.system,
"screen": system.screenWidth + "*" + system.screenHeight,
"version": App.version
}
const successFun = (reslove, data) => {
let obj = data
reslove(obj)
};
const errFun = (reslove, data) => {
if(data.statusCode==401){
loginOut();
return
}
let obj={
statusCode:data.statusCode,
errMsg:data.data['message']||data.data['msg']||'网络请求失败,请重新尝试!'
}
Animation.hideToast()
Animation.myToast('cancel',obj.errMsg);
reslove(obj)
}
module.exports = {
fetch: (url, data = {}, option = {},needToken=true) => {
let {
lodding = true, toast = true, method = 'get'
} = option;
return new Promise((reslove, reject) => {
if (lodding) {
wx.showLoading({
title: '加载中...',
mask: true
})
}
let env = App.config.baseApi;
let userInfo=store.getItem('userInfo')
let header={
"Content-Type": "application/json",
"clientInfo": JSON.stringify(clientInfo),
}
if(needToken){
header['Authorization']=store.getItem('token')['access_token']||null;
header['RefreshToken']=store.getItem('token')['refresh_token']||null;
}
if (method == 'delete' || method == 'DELETE'){
if (data){
let arr = [];
for (let key in data){
let value = data[key];
if (value === null || value === undefined || value == 'null') {
value = ''
};
if (Array.isArray(value)){
value = data[key].toString();
}
arr.push(`${key}=${value}`);
}
url += "?" + arr.join('&');
data = '';
}
}
wx.request({
url: env + url,
data,
method,
header,
success(res) {
if (res.statusCode == 200) { //请求成功
if (lodding) {
wx.hideLoading({
fail:()=>{
}
});
}
successFun(reslove, res.data)
} else { //请求失败
if (toast) {
wx.hideLoading({
fail:()=>{
}
});
//Animation.myToast('forbidden','请求超时');
} else {
if (lodding) {
wx.hideLoading({
fail:()=>{
}
});
}
}
errFun(reject, res)
}
},
fail: (err => {
let obj={
statusCode:-1,
data:{
message:err.errMsg
}
}
errFun(reject, obj)
})
})
})
}
};
const loginOut=function(){
store.clear("token");
store.clear("userInfo");
}