1. 程式人生 > >微信小程式 wx.request wepy 簡單封裝

微信小程式 wx.request wepy 簡單封裝

本文出自:

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

只有一個思路,具體大家可以自由發揮哦~