我们在开发小程序都会用到request请求,但是在每个请求都要写wx.request,这样就造成我们代码的重复率;
这边我对wx.request请求使用Promise进行二次封装,让代码灵活度变高,更实用。
import wxApi from '../wxapi'; //这个文件对微信的常用api进行二次封装,下次会更新
const wxapi = new wxApi();
import config from '../config'; //项目的配置文件
import userCache from '../user.js'; //用户管理js
import commonjs from '../commonjs'; //一些常用的公共js
const app = getApp();
export default class request {
constructor() {
this.config = {
id: userCache.getUser() ? userCache.getUser().id:''
}
}
//get
getRequest(url, data, isComplex = false) {
return this.requestAll(url, data, 'GET', isComplex)
}
//post 请求
postRequest(url, data, isComplex = false,isH5=false) {
return this.requestAll(url, data, 'POST', isComplex,isH5)
}
//put 请求
putRequest(url, data, isComplex = false) {
return this.requestAll(url, data, 'PUT', isComplex)
}
//delete 请求
deleteRequest(url, data, isComplex = false) {
return this.requestAll(url, data, 'DELETE', isComplex)
}
requestAll(url, data, method, isComplex = false) {
return new Promise((resolve, reject) => {
let fullurl = config.apiBaseUrl + url; //请求前缀
if (commonjs.startWith(url, 'http://') || commonjs.startWith(url, 'https://')) fullurl = url;
wx.request({
url: fullurl,
data,
header: {
'content-type': 'application/json'
},
method,
success: res => {
if (res.statusCode === 200) {
const {data} = res;
if (data.successed ||data.code==200) {
resolve(data)
} else {
if (!isComplex) {
wxapi.showToast(data.errmsg || '服务器错误')
resolve(data)
} else {
resolve(data)
}
}
} else {
reject(data)
wxapi.showToast(res.errMsg)
}
},
fail: () => {wxapi.showToast('请求超时');},
complete: (res) => {
resolve(res)
}
})
})
}
}
使用时
引入 import request from './request';
let requestApi=new request();
requestApi.postRequest(url, data, method, isComplex = false)
参数介绍
url:请求url
data:请求源数据
method:请求类型
isComplex :报错时是否返回信息