• 超好用超短的小程序请求封装


    超好用超短的小程序请求封装

     

    超好用超短的小程序请求封装,也不算特别特别短吧哈哈哈。但真的很好用的一个小程序请求封装,在请求的时候简短提高效率不需要将一样的东西重复写。下面就让大家看看这个封装是有多短,不够短的话也请别打我

    网上多数使用的小程序封装是在单独的一个js文件,再使用module.exports进行输出方法。我所介绍的封装方法有异曲同工之妙,只不过是写在app.js里边,省去了使用时必须引用文件的麻烦。

    app.js

    复制代码
    xcxPost(options = {}) {
        wx.showLoading({ mask: true, title: '', })
        wx.request({
          url: this.globalData.postUrl + options._url,
          data: options._data || {},
          method: "POST",
          dataType: "json",
          header: this.globalData.header,
          success: (res) => {
            if (res.data.errcode > 0) {
              if (typeof options._success == "function") {
                options._success(res.data);
              }
            } else {
              this.xcxErrorToast({ title: res.data.errmsg || '服务器返回错误!' });
              return;
            }
          },
          fail: (res) => {
            if (typeof options._fail == "function") {
              options._fail(res);
            }
            if (typeof options._fail == "string") { //请求失败的弹框提示
              wx.showToast({ title: options._fail, icon: 'loading', duration: 2000 });
            }
          },
          complete: (res) => {
            if (typeof options._complete == "function") {
              options._complete(res);
            }
            wx.hideLoading()
          }
        });
      },
    复制代码

    此处的this.globalData,是在app.js设置的,也就是小程序的全局属性,不了解的朋友请查阅小程序官方文档

    而以上封装具体的返回参数说明,请移步官方文档   https://developers.weixin.qq.com/miniprogram/dev/api/network-request.html#wxrequestobject

    复制代码
    App({
      globalData:{
        userInfo:{},
        postUrl: (wx.getExtConfigSync().request_url || '(后台接口地址)'),
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'Cookie': ''
        },
      }, 
    复制代码

    其他页面引用封装请求,比如 index.js

    复制代码
    /**
       * http请求
       * 获得banner图
       */
      getShopId(callBack) {
        app.xcxPost({
          _url:'pc_home_page/banner',// 你需要发起的请求;
          _data: { type: '1' },// 你需要传的请求参数;
          _success: (resp) => {//请求成功后的操作;if (resp.errcode > -1) {
              // this.globalData.shopId = resp.list.shopId;
              // this.globalData.domainUrl = resp.list.domain;
              if (callBack) {
                callBack()
              }
            }
          }
        }) },

    原文出处:https://www.cnblogs.com/web1/archive/2018/07/23/9353410.html
    分享文章如有侵权,版权等问题,请私信联系我,我将第一时间删除或修正。
  • 相关阅读:
    Hibernate学习笔记(一)
    mysql内联接、左联接、右联接
    mysql表数据增删改查、子查询
    mysql建表时候的五种约束
    mysql数据库基本数据类型
    nginx uwsgi flask相关配置
    关于爬虫数据的解析器设计
    Redis 七月小说网的爬虫缓存设计
    MariaDB 数据库迁移
    React Relay 实现
  • 原文地址:https://www.cnblogs.com/mhtss/p/9356158.html
Copyright © 2020-2023  润新知