微信小程序封装request请求

今日分享:微信小程序封装request请求

废话不多说 直接上代码~

1.utils 下创建utils.js文件

var api = require('../config/api.js');
var app = getApp();

/**
 * 封封微信的的request
 */
function request(url, data, method, loading) {
  data = data || {};
  if (loading) {
    wx.showLoading({
      title: '加载中',
    })
  }
  return new Promise(function(resolve, reject) {
    // api.apiRoot我自己定义的域名地址
    wx.request({
      url: api.apiRoot + url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function(res) {
        if (res.statusCode == 200) {
          if(res.data.code == 2) {
            // 登录过期 重新登录
            // app.login()
          } else if (res.data.code == 3) {
            // 清除登录相关内容
            try {
              wx.removeStorageSync('userId');
              wx.removeStorageSync('token');
              wx.removeStorageSync('phone');
            } catch (e) {
              // Do something when catch error
            }
            // 切换到登录页面
            wx.navigateTo({
              url: '/page/auth/login/login'
            });
            reject(res.data.msg);
          } else {
            resolve(res.data);
          }
        } else {
          reject(res.data.msg);
        }

      },
      fail: function(err) {
        reject(err)
        wx.showToast({
          title: "网络错误,请重新链接",
          duration: 1000
        });
      },
      complete: function () {
        if(loading) {
          wx.hideLoading();
        }
        
      }
    })
  });
}



module.exports = {
  request
}

2. api下创建各模块js文件 写接口地址 建议大家 模块化哈 代码如下:(user.js)

import util from '../utils/util'
//获取用户
function getContractInfo(params) {
  return util.request('xx/xx/info', params, 'GET');
}
// 这个是post请求 并添加loading
function ceshi(data) {
  return util.request('xx/xx/xx', data, 'POST', true);
}
module.exports = {
  getContractInfo: getContractInfo,
  ceshi: ceshi
}

3.页面js引用 只粘了部分给大家参考~

var ceshiServer = require('../../../api/user')

getOrderList() {
    const that = this
    const params = {
      isCustomer: false,
      current: 1,
      size: 10
    }
// 调用的上面xx/xx/info 这个接口
    ceshiServer.getContractInfo(params).then(res => {
        //接口返回 一系列处理
    })
  },

以上 结束 可能看起来 比较复杂 但我个人比较喜欢这么用 大家可以按照自己的代码风格封装 非常easy~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值