微信小程序封装get和post

最近开发小程序,根据小程序的API,我每发一次请求都要写一大串代码,而且都是重复的,所以我想封装一下,方便开发。
不多说直接贴代码:
首先我们先创建一个配置文件配置各种基础常量。
config.js

var config = {
  APPID: 'your id',
  BASE_URL:'your url',
}
//暴露接口
module.exports = config;

util.js

var config = require('config.js');//引入配置文件。
function Get(url,data,cb){
  wx.showNavigationBarLoading();//顶部显示loading效果
  wx.request({
    url: config.BASE_URL + url,
    data:data,
    success:(res) => {
      typeof cb == "function" && cb(res.data,"");
      wx.hideNavigationBarLoading();//顶部隐藏loading效果
    },
    fail:(err) => {
      typeof cb == "function" && cb(null,err.errMsg);
      console.log("get 请求:" + config.BASE_URL);
      console.log(err)
      wx.hideNavigationBarLoading();
    }
  })
};

function Post(url, data, cb) {
  wx.request({
    method: 'POST',
    url: config.BASE_URL + url,
    data: data,
    header:{
      "Content-Type": "application/x-www-form-urlencoded"//跨域请求
    },
    success: (res) => {
      typeof cb == "function" && cb(res.data, "");
    },
    fail: (err) => {
      typeof cb == "function" && cb(null, err.errMsg);
      console.log("post 请求:" + config.BASE_URL);
      console.log(err);
    }
  });
};
//暴露接口
module.exports = {
  httpGet: Get,
  httpPost: Post
}

其中的cb作为一个回调函数,执行返回成功时的操作。至此我们成功封装了微信小程序的get和post两个方法。
比如在index.js使用如下:

var http = require('../../utils/util.js');
Page({
  data: {
  },
  onLoad:function(){
   http.httpGet("?action=index", {appid: config.APPID,}, function (res) {
      console.log(res);
      });
    });
  }
 })

就像jquery的$.get(),post的使用方法都是一样的。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

kitt15

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

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

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

打赏作者

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

抵扣说明:

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

余额充值