前言
最近学习了一下wepy微信小程序的开发,就简单的介绍一下怎么构建项目,工欲善其事必先利其器,今天主要说的还是对wepy.request的二次封装。封装之后可以更好的调用。
全局安装wepy
npm install wepy-cli -g
创建项目
wepy new myproject
切换至项目目录
cd myproject
安装依赖
npm install
开启实时编译
wepy build --watch
好了项目已经构建完成,接下来就是重点,对wepy.request的封装。
首先我们新建一个名为util的文件夹,再新建一个名为httpRequest.js的文件
好了,废话不多说接下俩开始封装我们的请求方法,代码当中都有注释:
httpRequest.js
// 引入 wepy
import wepy from 'wepy'
export class RequestService {
static httpHandlerError(info, callBack, errTip) {
wepy.hideLoading()
if (info.statusCode === 200) {
return false
} else {
if (info.data.status === 401) {
wepy.redirectTo({
url: 'index'
})
}
let errorInfo = ''
if (errTip) {
errorInfo = errTip
} else {
if (info.data.errMsg) {
errorInfo = info.data.errMsg
} else {
errorInfo = '也许服务器忙!'
}
}
wepy.showToast({
title: errorInfo,
icon: 'loading',
duration: 3000
})
if (callBack) {
callBack()
}
return true
}
}
static sendRequest() {
const that = this
return {
_sucCallback: null,
_failCallback: null,
_method: 'GET',
_data: {},
_header: {'content-type': 'application/json'},
_url: '',
send: function() {
wepy.request({
header: this._header,
data: this._data,
url: this._url,
method: this._method,
success: (res) => {
let error = that.httpHandlerError(res, this._failCallback)
if (error) return
this._sucCallback(res)
},
fail: (res) => {
this._failCallback()
}
})
return this
},
success: function(callback) {
this._sucCallback = callback
return this
},
fail: function(callback) {
this._failCallback = callback
return this
},
url: function(url) {
this._url = url
return this
},
data: function(data) {
this._data = data
return this
},
header: function(header) {
this._header = header
return this
},
method: function(method) {
this._method = method
return this
}
}
}
}
封装完了之后我们来调用下
// 引入httpRequest
import { RequestService } from './util/httpRequest'
// 调用方式
RequestService.sendRequest().url('url').header({
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
}).method('POST').data({
}).success(res => {
console.log(res)
}).send()
到现在为止我们把wepy.rewuest就封装完了,我把代码放到git上了传送门
希望小哥哥小姐姐们多多star,多多支持,有什么疑问可以在github上问我,谢谢。点赞的小哥哥小姐姐最可爱,哈哈哈。。。



