微信小程序 wx.request wepy 简单封装(一)

import sha1 from './sha1'

// sign

// 签名
function sign (signObj = {}) {
  ... // 自行加密
  return signObj
}

// GET请求
function GET (requestHandler, isShowLoading) {
  return request('GET', sign(requestHandler), isShowLoading)
}

// POST请求
function POST (requestHandler, isShowLoading) {
  return request('POST', sign(requestHandler), isShowLoading)
}

function request (method, requestHandler, isShowLoading = true) {
  // 加密
  let params = requestHandler.params
  isShowLoading && wx.showLoading && wx.showLoading({title: '加载中...'})
  return new Promise((resolve, reject) => {
    wx.request({
      url: requestHandler.url,
      data: params,
      method: method, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        'Content-Type': method === 'POST' ? 'application/x-www-form-urlencoded' : 'application/json'
      },
      success: function (res) {
        isShowLoading && wx.hideLoading && wx.hideLoading()
        // 解密
        if (res.data.success) {
          resolve(res.data.data)
        } else {
          reject(res.data.data)
          // throw new Error('Network request success but data state not success')
        }
      },
      fail: function () {
        // 因为hide会让showToast隐藏
        isShowLoading && wx.hideLoading && wx.hideLoading()
        wx.showToast({
          title: '网络请求失败',
          icon: 'success',
          image: '../style/images/toast_info.png',
          duration: 1500
        })
        reject(new Error('Network request failed'))
        // throw new Error('Network request failed')
      },
      complete: function () {
      }
    })
  })

}

module.exports = {
  get: GET,
  post: POST
}

使用也很简单

import { API_URL, commom, httpUtils } from '../config'

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

友情链接更多精彩内容