首页 > 微信 > 详细

微信小程序-request,promise请求封装DEMO

时间:2021-03-01 18:09:32      阅读:31      评论:0      收藏:0      [点我收藏+]
app.js
  onLaunch() {
 
    //判断运行环境
    if (typeof __wxConfig == "object") {
      let version = __wxConfig.envVersion;
      if (version == "develop") {
        //工具或者真机 开发环境
        this.globalData.baseUrl = ‘http://127.0.0.1/‘
      } else if (version == "trial") {
        //测试环境(体验版)
        // this.globalData.baseUrl = ‘‘
      } else if (version == "release") {
        //正式环境
        this.globalData.baseUrl = ‘‘
      }
    }
 
    //保存设备信息
    wx.getSystemInfo({
      success: function (res) {
        wx.setStorageSync(‘system_version‘, res.system)
        wx.setStorageSync(‘phone_modle‘, res.model)
      }
    })
  },
globalData: {
    baseUrl: ‘http://127.0.0.1/‘, //本地环境
  }
alert(msg){
    wx.showModal({
      content: msg,
      showCancel:false,
      confirmColor:‘#00bc8d‘
    })
  },
  tip(msg){
    wx.showToast({
      title: msg,
      icon:‘none‘
    })
  },
 
微信小程序http.js
const app = getApp();
//o -> {params:{},url:‘‘} 请求参数,url为必须的
function GET(o) {
  return request(‘GET‘, o);
}
function POST(o) {
  return request(‘POST‘, o);
}
function request(method,o) {
  return new Promise(function (resolve, reject) {
    const requestData = args(o)
    wx.showLoading({
      title: ‘请求中...‘,
      mask:true
    })
     wx.request({
      url: app.globalData.baseUrl + o.url,
      data: requestData,
      method: method, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        ‘Content-Type‘: ‘application/json‘
      }, 
      success: function (res) {
        wx.hideLoading();
        if (res.statusCode == 200) { //网络请求状态
          if(res.data.code == 200){ //后端返回code ==200成功,其他失败
            resolve(res)
          }else{
            reject(res);
          }
        } else {
          app.alert(‘请求出错!‘)
        }
      },
      fail: function (e) {
        wx.hideLoading()
        app.alert(‘请求失败!‘)
      }
    })
  })
}
//公共参数
function args(o) {
  return {
    mobile: wx.getStorageSync(‘phoneNumber‘)||‘‘,
    imei: ‘smallProgram‘,
    token: wx.getStorageSync(‘token‘)||‘‘,
    methodName: o.url.split(‘/‘).join(‘.‘),
    source: ‘12‘,
    phone_modle: wx.getStorageSync(‘phone_modle‘),
    time_stamp: new Date().getTime() + ‘‘,
    system_version: wx.getStorageSync(‘system_version‘),
    app_version: ‘1.0.0‘,
    ip_address: ‘‘,
    parameter: o.params||{}
  }
}
module.exports = {
  ‘GET‘: GET,
  ‘POST‘: POST,
}
 
使用示例:
const http = require(‘http.js‘)
let params = {
  url:‘name/contraller‘,
  prams:{}//   如果有参数传这个对象里,反则无需这个对象
}
http.POST(params).then((res)=>{
  //do something when request success!
}).catch((res)=>{
  app.tip(res.data.message)
})

微信小程序-request,promise请求封装DEMO

原文:https://www.cnblogs.com/Joseph-lrc/p/14464445.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!