小程序request二次封装

原本用法

 wx.request({
	  url: 'test.php', //仅为示例,并非真实的接口地址
	  method:“POST,
	  data: {  },
	  header: {
	    'content-type': 'application/json' // 默认值
	  },
	  success (res) {
	    console.log(res.data)
	  },
	  fail(err){
	  }
 })

小曲封装

// 优化方案:对于某些接口(例如不需要登录),可以进行请求拦截,减少服务器请求次数

// 封装网络请求的方法,结合promise 
const app = getApp()
module.exports = (url, data, type = 0) => {
// 小接口不走加载中提示框
// 优化方案:可以使用白名单,Map方法处理特殊的接口
  if (url == "circle/addUserLike" || url == 'circle/delUserLike' || url == 'circle/addUserCollect' || url == 'circle/delUserCollect' || url == 'circle/addUserAttention' || url == 'circle/delUserAttention' || url == 'user/selectVerificationCode' || url == 'user/sendCode' || url == 'user/clearOnecollect' || url == 'user/goodsCollectionlist' || url == 'user/addressDel' || url == 'user/addressList' || url == 'user/sureOrder' || url == 'goods/addGoodsCollect' || url == 'goods/delGoodsCollect' || url == 'goods/addGoodsRemind' || url == 'goods/addGoodsBidLog') {

  } else {
    wx.showLoading({
      title: '加载中...'
    });
  }
  // 返回一个promise实例
  return new Promise((resolve, reject) => {
    // 不止一个域名
    // 优化方案:可以封装两个方法,
    let href
    if (type) {
      href = 'http://auction.dlpm.net.cn/api/' //PHP域名
    } else {
      href = 'http://sale.dlpm.net.cn/' //Java域名
    }
    // 小程序请求
    wx.request({
      url: href + url,
      data: data,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'token': wx.getStorageSync('token'),
        // 'token': '1234567'
      },
      method: "POST",
      success(res) {
        console.log(res.data);
        if (res.statusCode == 200) {
          // 登录过期,返回-1,正常返回1,错误返回0
          if (res.data.result == -1) {
            wx.getSetting({
              success: res => {
                if (res.authSetting['scope.userInfo']) {
                  // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
                  wx.getUserInfo({
                    success: res => {
                      app.globalData.userInfo = res.userInfo;
                      if (app.userInfoReadyCallback) {
                        app.userInfoReadyCallback(res)
                      }
                    }
                  })
                  wx.reLaunch({
                    url: '/pages/login/numberLogin/numberLogin',
                  })
                } else {
                  wx.switchTab({
                    url: '/pages/my/my'
                  })
                }
              }
            })
            return;
          } else if (res.data.result == 1) {
            resolve(res.data.data);
          } else if (res.data.result == 0) {
            // 特殊的单独提醒
            // if (url == "user/userLogin") {
            //   wx.showToast({
            //     title: '操作频繁,请稍后重试',
            //     icon: 'none',
            //     duration: 2000
            //   })
            // } else{
            // 解决错误信息弹窗一闪而过
            wx.showLoading();
            wx.hideLoading();

            setTimeout(function () {
              wx.showToast({
                title: res.data.msg,
                icon: 'none',
                duration: 2000
              })
            }, 0)
            // }
            // reject(res.data);   //可以传入失败回调
          }
        } else {
          wx.showToast({
            title: '接口请求失败,接口状态' + res.statusCode,
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail() {
        wx.showToast({
          title: '接口调取失败,请检查网络连接',
          icon: 'none',
          duration: 2000
        })
      },
      complete() {
        wx.hideLoading();
      }
    })
  })
}

调用index.js
// 优化方案:可以在app.js 中引入公共方法request,然后复制给wx对象
wx.request=request,然后即可全局访问
在页面里直接使用wx.http().then()即可

const http= require('../../utils/request.js');
wx.http=http
onload(){
    http('/api/mobile/index.php?w=goods&t=goods_detail',{
      goods_id: '100165'
    }).then(data=>{
        console.log(data)  // 成功回调
         wx.showToast({
          title: '成功',
          icon: 'none',
          duration: 2000
        })
      }).catch(res=>{
        console.log(res)  //失败回调
      }
    )
 } 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小曲曲

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

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

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

打赏作者

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

抵扣说明:

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

余额充值