小程序 api接口封装

  • 基于Promise封装wx.request

    新建一个http.js代码如下:
    
      const Config = {
        api_base_url:'https://www.xxxxx.com/', //填写你的服务器api地址 
        version:1 //版本
      }
      class HTTP {
        request({ url, data = {}, method = 'POST'}) {
          return new Promise((resolve, reject) => {
            this._request(url, resolve, reject, data, method)
          })
        }
        _request(url, resolve, reject, data = {}, method = 'POST') {
          const role_type = wx.getStorageSync('roleType')
          const baseParam = { //基本参数
            version: Config.version,
            token: wx.getStorageSync('token')
          }
          let data1 = Object.assign(baseParam, data)
          wx.request({
            url: Config.api_base_url + url,
            method: method,
            data: data1,
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },success: (res) => {
              //320 未登录跳转登录页
              if (res.data.code == 320) {
                  setTimeout(() => {
                    wx.navigateTo({
                      url: '/pages/login/login'
                    })
                  }, 300);
                  return false;
              }
              if (res.data.success) {
                resolve(res.data.data)
              }else{
                reject(res)
                this._show_error(res.data.msg || '返回错误!')
              }
      
            },fail: (res) => {
              reject(res.data.msg)
              this._show_error('服务器繁忙')
            },
            complete:(res)=>{
              
            }
          })
        }
      
        //封装提示语
        _show_error(msg) { 
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 3000
          })
        }
      }
      export {
        HTTP
      }
    
    
  • 页面上使用接口

    代码示例如下:
    //index.js
    import {
      HTTP
    }
    from "../../utils/http.js"
    const http = new HTTP();
    
    Page({
        /**
          * 页面的初始数据
          */
        data: {
          goodsList:[]
        },
    
        /**
        * 生命周期函数--监听页面加载
        */
        onLoad: function (options) {
          this.getData()
        },
    
        getData() {
          http.request({
            url: 'goods/get_goods_info', //填写自己的服务器接口
            data:{
              page:1,
              size:10
            }  //传自己所需的参数
          }).then(res => {
            this.setData({
              goodsList: res
            })
          })
        }
    
    })
    
    
    
    
  • 上传图片接口封装

    封装 wx.uploadFile 代码示例如下:
     //uploadimg.js 上传图片的封装,可上传多张
    const uploadImg = (data)=>{
      return new Promise((resolve, reject) => {
        _uploadimg(data, resolve, reject)
      })
    }
    _uploadimg(data, resolve, reject) {
      let that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
      wx.uploadFile({
        url: api_base_url + data.url,
        filePath: data.path[i],
        name: 'img_url',  //对应后台name
        formData: {
          token: wx.getStorageSync("token")
        },
        success: function (res) {
          success++;
          let data = JSON.parse(res.data)
          if (data.success) {
            resolve(res.data.data)
          }
          else {
            reject(data.msg)
            console.log(i);
        },
        fail: function (res) {
          fail++;
          console.log('fail:' + i + "fail:" + fail);
        },
        complete: () => {
          console.log(i);
          i++;  //这个图片执行完上传后,开始上传下一张            
          if (i == data.path.length) {   //当图片传完时,停止调用          
            console.log('成功:' + success + " 失败:" + fail);
          } else {  //若图片还没有传完,则继续调用函数                
            data.i = i;
            data.success = success;
            data.fail = fail;
            that.uploadimg(data);
          }
        }
      })
    }
    export { uploadImg }
    
    
    页面上调用代码示例如下:
    //wxml code
    <view class="title">上传门店主图</view>
    <view bindtap="chooseImage">上传图片</view>
    
    
    //js code
    import {
      uploadImg
    } from "uploadimg.js"
    Page({
      //点击上传的按钮事件
      chooseImage(e){
          wx.chooseImage({
              count: 1,
              sizeType: ['original', 'compressed'],
              sourceType: ['album', 'camera'],
              success (res) {
                  // tempFilePath可以作为img标签的src属性显示图片
                  const tempFilePaths = res.tempFilePaths
                  //调整封装好的uploadImg
                  uploadImg({
                    url:'store/edit_store_img',
                    path: tempFilePaths
                  })
              }
          }) 
      }
      
    })