• 微信小程序封装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值进一步判断,特定错误码统一处理,比如跳转登录页面等。

  • 相关阅读:
    Hello,cnblogs!
    本地搭建IIS服务器
    thinkPHP相关
    网页中经常用到的<hr / >标签的样式
    JS三元表达式
    ZUI开发人员选项
    XWindow、Server、Client和QT、GTK之间的关系
    深度桌面操作系统架构设计
    关于linux图形界面的基本知识
    linux各发行版之间的区别
  • 原文地址:https://www.cnblogs.com/yujihaia/p/7459434.html
Copyright © 2020-2023  润新知