import bus from ‘@/utils/bus.js’
import md5 from ‘md5’;
import objKeySort from ‘@/utils/sort.js’
import store from ‘@/store’
// function isObj(obj){ //递归加user_info_dto
// //如果传进来的个别对象,那么就判断有没有user_info_dto,没有的话加一项空的
// if(obj instanceof Object){

// for(let key in obj){
// if(obj[key] instanceof Object || obj[key] instanceof Array){
// if(obj[key] == {}){

// }else{
// obj[key] = isObj(obj[key])
// }
// }
// }
// if(!obj.user_info_dto){
// obj.user_info_dto = {}
// }
// }
// if(obj instanceof Array && obj.length > 0){
// for(let i = 0 ; i < obj.length ; i++){
// obj[i] = isObj(obj[i])
// }
// }
// return obj
// }
class Http {
constructor() {
this.showModal = false
}
post(options = {}) {
return this.request({
…options,
method: ‘POST’
})
}

delete(options = {}) {
return this.request({
…options,
method: ‘DELETE’
})
}

get(options = {}) {
return this.request({
…options,
method: ‘GET’
})
}

request(options = {}) {
let {
url, method, data, config,isToken,noToken
} = options
config = typeof config === ‘object’ ? config : {}
config = {
dialog: true,
…config
}
let header = {}
// const Authorization = ‘Bearer ’ + wx.getStorageSync(‘token’)
header = {
// Authorization
}
// console.log(isToken,‘sssssssssssssss’);

if(noToken){

}else{
  if(wx.getStorageSync('token')){
    header['Authorization'] = `Bearer ${wx.getStorageSync('token')}`;
  }else{

  }
}

// if(isToken){

// }else{
//   header['Authorization'] = `Bearer ${wx.getStorageSync('token')}`;
// }
//设置公用签名
let apiTime = Date.parse(new Date()).toString().substr(0,10);
header['Accept-ApiKey'] = '6aef6c94225c4d1';
header['Accept-ApiTime'] = apiTime;
header['device-type'] = 'wxmp';
let beforParams = '';
let afterParams = '';
let params = data;
//判断传过来的参数是否为对象
if(params instanceof Object){
  params = objKeySort(params) //对象进行字典排序

  for(let i in params){
    if(typeof params[i] == 'number'){
      params[i] = params[i].toString()
    }
    if(params[i]){
      if((params[i] instanceof Array) && (params[i].length == 0)){
        delete params[i]
      }else{
        if(params[i] instanceof Array){
          beforParams += `${i}=${JSON.stringify(params[i])}`
        }else{
          beforParams += `${i}=${params[i]}`
        }
        
      }
      
    }else{
      delete params[i]
    }
  }
}

afterParams = beforParams+url+'1c2653ca2aab4e0'+apiTime;
// data = params //去掉空属性并且排序后的data

// ApiSign
let mdD = md5(afterParams);

header['Accept-ApiSign'] = mdD;

return new Promise((resolve, reject) => {
  //cconsole.log(this.$store)
  //  
  wx.request({
    url: process.env.API_URL + url,
    method,
    data:params,
    header,
    success: (res) => {
      // wx.hideLoading();  
      // 判断网络
      // if (res.statusCode == 404) {
      //   reject();
      //   return false;
      // } else if (res.statusCode != 200) {
      //   this.openModal({
      //     reject,
      //     content: '网络出错,稍后在试!',
      //     res
      //   })
      //   return false;
      // }
      // const {code, message} = res.data
      if(res.statusCode == '204' || res.statusCode == '200') {
        // 成功返回数据
        // console.log(77777777777777777777,isObj(res.data));
        // reject(res.data)
        resolve(res.data);
      } else {
        wx.showToast({
          title: res.data.message,
          icon: 'none'
        })
        reject(res.data)
      }
      if(res.statusCode == '401'){
        //登录状态过期,清空登录信息
        // console.log(store);
        //  
        this.openModal({
          reject,
          content: '登录已失效,请重新登录',
          confirmText: '去登录',
          showCancel: true,
          success: res =>{
            if(res.confirm){
                wx.removeStorageSync('token')
                wx.removeStorageSync('user')
                wx.clearStorage()
                store.dispatch("setUser", null);
                store.dispatch("setToken", null);
                bus.$emit('clearTokenAndUser')
                // wx.switchTab({
                //   url: "/pages/mine/main",
                //   fail: res => {
                //   }
                // })
                wx.navigateTo({
                  url: "/pages/packages/lesson/tologin/main",
                })
            }
          }
        })
      }
      // else if(code === '-2') {
      //   this.openModal({
      //     reject,
      //     content: '登录已失效,请重新登录',
      //     confirmText: '去登录',
      //     showCancel: true,
      //     success: (res) => {
      //       if(res.confirm) {
      //         // wx.removeStorageSync('token')
      //         // wx.removeStorageSync('user')
      //         // this.$store.dispatch("setUser", null);
      //         // this.$store.dispatch("setToken", null);
      //         bus.$emit('clearTokenAndUser')
      //         wx.switchTab({
      //           url: "/pages/mine/main",
      //           fail: res => {
      //             console.log(res)
      //           }
      //         })
      //       }
      //     },
      //     res: res.data
      //   })
      //   //reject(res.data)
      // } else if (code === '-3') {
      //   wx.showToast({
      //     title: '不能包含敏感词汇',
      //     icon: 'none'
      //   })
      //   reject(res.data)
      // } else {
      //   if(config.dialog) {
      //     this.openModal({
      //       reject,
      //       content: message,
      //       res: res.data
      //     })
      //   } else {
      //     reject(res.data)
      //   }
      // }
    },
    fail: (error) => {
      // 失败
      // wx.hideLoading();
      this.openModal({
        reject,
        content: '没连接到网络',
        res: error
      })
    },
    complete: function() {
      // gezc: 别加 hideloading
      // wx.hideLoading();
    }
  });
})

}

// 显示提示框
openModal(options = {}) {
const {
content,
reject,
res,
showCancel = false,
confirmText = ‘确定’,
success = () => {}
} = options
if(!this.showModal) {
this.showModal = true
wx.showModal({
content,
showCancel,
confirmText,
success,
complete: () => {
this.showModal = false
reject(res)
}
})
} else {
reject(res)
}
}
}

export default new Http()


版权声明:本文为weixin_53834770原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_53834770/article/details/119822729