微信小程序封装http访问网络库实例代码

之前都是使用LeanCloud为存储,现在用传统API调用时做如下封装

var HOST = 'http://localhost/lendoo/public/index.php/';
// 网站请求接口,统一为post
function post(req) { 
//发起网络请求
 wx.request({
 url: HOST + req.uri, 
 data: req.param, 
 header: {
   "content-type": "application/x-www-form-urlencoded"
 },
 method: 'POST', 
 success: function (res) {
  req.success(res.data)
 }, 
 fail: function (res) {
   console.log(res);
 }
 })
}
// 导出模块
module.exports = { post: post
}

然后前端调用就可以这样做了:

var http = require('../../utils/http.js');
...
 http.post({ 
  uri: http.orderListUri, 
  param: {
   third_session: wx.getStorageSync('third_session')
  },  
   success: function (data) {
   that.setData({
    orderList: data
  });
  }
 });

一般对自己写的接口给自己用的时候,method方法或header都是约定好的,所以不用重复书写。

1 header: {
2    "content-type": "application/x-www-form-urlencoded"
3   },
4 method: 'POST'

而fail回调方法也可以统一处理;进一步地,也可以对success回调里的针对code值进一步判断,特定错误码统一处理,比如跳转登录页面等。

转载于:https://www.cnblogs.com/d-xs/p/6917225.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值