封装小程序请求接口的方法

let rootUrl = " ";//具体接口域名根据你的实际情况填写
function getData(url, data, cb) {

wx.request({
url: rootUrl + url,
data: data,
method: ‘get’,
header: {
“Content-Type”: “json”, //get请求时候

},
success: function (res) {
  wx.hideLoading();
  if (res.data.err==-110){//未授权登录
    wx.setStorageSync('userInfo','')
  } 
  return typeof cb == "function" && cb(res.data)
},
fail: function () {
  wx.hideLoading();
  return typeof cb == "function" && cb(false)
}

})
}

function postData(url, data, cb) {

wx.request({
url: rootUrl + url,
data: data,
method: ‘post’,
header: {
“Content-Type”: “application/x-www-form-urlencoded”, //POST请求的时候这样写

},
success: function (res) {
  wx.hideLoading();
  if (res.code == 101) {//未授权登录
    wx.showModal({
      title: '提示',
      content: '登录失效,请重新登录',
      showCancel: false,
      success(res) {
        
      }
    })

  } 
  return typeof cb == "function" && cb(res.data)
},
fail: function (e) {
  wx.hideLoading();
  console.log(e)
  return typeof cb == "function" && cb(false)
}

})
}

module.exports = {
getData: getData, //暴露一个方法
postData:postData
}
js名改为netUtil.js
页面中引用var netUtil = require("…/…/utils/netUtil.js");
//post请求方法
toupload() {
wx.showLoading({ title: ‘数据加载中’, });
let params = {
}
netUtil.postData(‘upload’, params, (datas) => {
if (datas.code == 200) {
wx.hideLoading()
this.setData({
// service: datas.result

    })
  } else {
    wx.showToast({
      title: datas.msg,
      icon: 'none'
    })
  }
})

},
//get请求方法
toupload() {
wx.showLoading({ title: ‘数据加载中’, });
let params = {
}
netUtil.getData(‘upload’, params, (datas) => {
if (datas.code == 200) {
wx.hideLoading()
this.setData({
// service: datas.result

    })
  } else {
    wx.showToast({
      title: datas.msg,
      icon: 'none'
    })
  }
})

},

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值