小程序简单封装http访问网络库

缘起

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

文档出处:https://mp.weixin.qq.com/debug/wxadoc/dev/api/network-request.html

代码如下:

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都是约定好的,所以不用重复书写。

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

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

经过上述处理,是不是变得简洁了?

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容