您的位置:首页 > 产品设计 > UI/UE

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

2017-10-28 11:18 1866 查看
本文出自:

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


只有一个思路,具体大家可以自由发挥哦~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  微信 小程序 request