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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wyk304443164/article/details/78374194

本文出自:

http://blog.csdn.net/wyk304443164

很简单

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()
        })

只有一个思路,具体大家可以自由发挥哦~

猜你喜欢

转载自blog.csdn.net/wyk304443164/article/details/78374194