小程序封装get和post请求


// 封装gat
function get(url,date,res){
  wx.request({
    url: url, //仅为示例,并非真实的接口地址
    data: date,//数据格式{'name':1,'xx':2}
    header: {'content-type': 'application/json'},// 默认值get,
    method:'get',
    dataType:"json",
    responseType:"text",
    success (e) {
      res(e);
    },
    fail: ()=>{
      wx.showToast({
        title: '系统繁忙,请联系管理员',
        icon: 'none',
        duration: 2000
      })
    }
  })
}
// 封装post
function post(url,date,res){
  wx.request({
    url: url, //仅为示例,并非真实的接口地址
    data: date,//数据格式{'name':1,'xx':2}
    header: { "Content-Type": "application/x-www-form-urlencoded"},//post
    method:'post',
    dataType:"json",
    responseType:"text",
    success (e) {
      res(e)
    },
    fail: ()=>{
      wx.showToast({
        title: '系统繁忙,请联系管理员',
        icon: 'none',
        duration: 2000
      })
    }
  })
}
var _this = this;
// 登录
function name_login(url,openid,e){
  wx.getUserProfile({
    desc: '用于完善会员资料', 
    success: (res) => {
      wx.setStorage({
        key:"name_login",
        data:res.userInfo
      })
      var data = {'equipment':1,'appid':'111','openid':openid,"user":res.userInfo.nickName,'img':res.userInfo.avatarUrl};
      var urls = url+"/wxapp/add";
      post(urls,data,es=>{
        console.log(es)
        if(es.data.message == "添加成功"){
          var da = es.data.data;
        }else{
          //用户已存在
          var da = es.data.data[0];
        }
        wx.setStorage({
          key:"username",
          data:da
        })
      })
      e(res)
    }
  })
}

// 使用
// const app = getApp()
// var http = require("../../utils/http/https")
// var url = app.globalData.apphttp+"/wxapp/1";
// http.get(url,1,res=>{
//   console.log(res)
// })

module.exports = {
  get,
  post,
  name_login,
}

 

 

微信小程序封装get和post请求接口可以提高开发效率和代码复用性。我们可以创建一个封装网络请求的工具类,定义两个方法,分别用于发送get请求post请求。 首先,我们创建一个util.js文件,定义一个request方法,用于发送请求。该方法接收四个参数:url(请求地址)、method(请求方法,可选值为'GET'或'POST')、data(请求参数,可选值为空对象{})、header(请求头部信息,可选值为{"content-type": "application/json"})。在该方法内部,首先使用wx.request方法发送请求,并将参数传入request方法中。然后在success和fail回调方法中,分别处理请求成功和请求失败的情况。对于请求成功的情况,可以使用Promise封装处理成功的状态,将返回的数据传递给then方法。对于请求失败的情况,可以使用Promise封装处理失败的状态,将失败的信息传递给catch方法。 在util.js文件中,我们定义两个方法:get和post,分别用于发送get请求post请求。在这两个方法内部,我们直接调用request方法,并传递相应的参数。对于get请求,我们将method设置为'GET',将data设置为空对象,即可发送get请求。对于post请求,我们将method设置为'POST',将data设置为我们要发送的参数,即可发送post请求。 使用封装的get和post请求接口,可以简化我们发送网络请求的代码。只需在需要发送请求的地方,引入封装的util.js文件,调用相应的get或post方法,并传递相应的参数即可。 通过封装get和post请求接口,我们可以实现网络请求的复用,提高开发效率,并且可以统一处理请求成功和失败的情况,使代码更加简洁和可维护。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大得369

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值