最近研究微信小程序,微信小程序默认带的 wx.request也好用 但是每个页面都用那个写起来有点长,所以想办法做个简单封装,以方便后期使用。刚开始百度搜的一篇文章,里面有封装好的js,想直接拿来用,大佬原文链接:如何简单封装微信小程序请求_仗剑走天涯的博客-CSDN博客
但是复制过来之后一直报错,后来找到原因是我项目是设置了将js编译成ES5。
原JS如下:
const baseUrl='http://192.168.10.99:8085'
const tips = {
440001: '抱歉,服务出现了一点异常',
440002: '您没有权限操作',
440003: '您当前未登录',
440004: '您的登录已经失效,请重新登录',
440005: '抱歉,服务出现了一点异常',
2014: '手机验证码失效,请重新获取',
2015: '手机验证码错误,请请重新输入',
2021: '更新用户信息失败',
2030: '用户名不存在',
2031: '绑定企业用户失败',
2034: '此用户已绑定过了微信用户',
2072: '图形验证码已失效',
2073: '验证码错误',
3022: '无效验证码',
3021: '请勿重复发送',
3020: '验证码发送失败'
}
class HTTP {
request({url,data={}, method='GET'}) {
return new Promise((resolve, reject) => {
this._request(url, resolve, reject, data, method);
}).catch((e) => {
wx.showToast({
title: '抱歉,出现了一个错误',
icon:'none',
duration:2000
})
});
}
_request(url, resolve, reject, data={}, method='GET') {
let token = wx.getStorageSync('token');
let openId = wx.getStorageSync('openId');
wx.request({
url: baseUrl + url,
method: method,
data: data,
header: {
'content-type': 'application/json',
'appId': config.appId,
'token': token || '',
'openId': openId || '',
},
success: (res) => {
let code = res.statusCode.toString();
if (code.startsWith('2')) {
if (res.data.code === 440005) {
reject()
const error_code = res.data.code;
this._show_server_error(error_code);
} else {
resolve(res.data);
}
} else {
reject()
const error_code = res.data.code;
this._show_error(error_code);
}
},
fail: (err) => {
reject();
this._show_error(1);
}
})
}
_show_error(error_code){
if(!error_code){
error_code = 1
}
const tip = tips[error_code]
wx.showToast({
title: tip?tip:tips[1],
icon:'none',
duration:2000
})
}
_show_server_error(error_code) {
if(!error_code){
error_code = 440005
}
const tip = tips[error_code]
wx.showToast({
title: tip?tip:tips[1],
icon:'none',
duration:2000
})
}
}
export { HTTP };
报错如下:
VM115 WAService.js:2 TypeError: (0 , _http.request) is not a function
at getPage (index.js? [sm]:4)
at Ui.getShowData (index.js? [sm]:54)
at Ui.onLoad (index.js? [sm]:29)
at Ui.<anonymous> (VM115 WAService.js:2)
at Ui.o.__callPageLifeTime__ (VM115 WAService.js:2)
at ir (VM115 WAService.js:2)
at VM115 WAService.js:2
at cr (VM115 WAService.js:2)
at a.<anonymous> (VM115 WAService.js:2)
at K.<anonymous> (VM115 WAService.js:2)(env: Windows,mp,1.05.2107090; lib: 2.19.5)
那个class好像是ES6的语法,我不懂,而且一直报错不知道咋调,所以只能修改原来的代码,修改后变成了这样:
const baseUrl = 'http://192.168.10.99:8085'
const tips = {
440001: '抱歉,服务出现了一点异常',
440002: '您没有权限操作',
440003: '您当前未登录',
440004: '您的登录已经失效,请重新登录',
440005: '抱歉,服务出现了一点异常',
2014: '手机验证码失效,请重新获取',
2015: '手机验证码错误,请请重新输入',
2021: '更新用户信息失败',
2030: '用户名不存在',
2031: '绑定企业用户失败',
2034: '此用户已绑定过了微信用户',
2072: '图形验证码已失效',
2073: '验证码错误',
3022: '无效验证码',
3021: '请勿重复发送',
3020: '验证码发送失败'
}
function request({url, method='GET',data={}}) {
try {
return new Promise((resolve, reject) => {
_request(url, resolve, reject, data, method);
});
} catch (e) {
wx.showToast({
title: '抱歉,出现了一个错误',
icon: 'none',
duration: 2000
});
}
}
function _request(url, resolve, reject, data={}, method='GET') {
let token = wx.getStorageSync('token');
let openId = wx.getStorageSync('openId');
wx.request({
url: baseUrl + url,
method: method,
data: data,
header: {
// 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'content-type': 'application/json',
'Authorization': token || '',
'openId': openId || '',
},
success: (res) => {
if (res.statusCode === 200) {
if (res.data.code === 440005) {
reject()
const error_code = res.data.code;
_show_server_error(error_code);
} else {
resolve({
data: res.data,
status: res.statusCode
});
}
} else {
reject()
const error_code = res.data.code;
_show_error(error_code);
}
},
fail: (err) => {
reject();
_show_error(1);
}
})
}
function _show_error(error_code){
if(!error_code){
error_code = 1
}
const tip = tips[error_code]
wx.showToast({
title: tip?tip:tips[1],
icon:'none',
duration:2000
})
}
function _show_server_error(error_code) {
if(!error_code){
error_code = 440005
}
const tip = tips[error_code]
wx.showToast({
title: tip?tip:tips[1],
icon:'none',
duration:2000
})
}
function _show_error_text(error) {
wx.showToast({
title: error,
icon:'warning',
duration:2000
})
}
module.exports = {
request: request
}
使用示例(截图展示项目结构以便理解导入):
import {request} from '../http.js'
export function getPage(params) {
return request({
url: '/missingPet/showData',
methos: 'get',
data: params
}
)
}
//index.js
//获取应用实例
import {getPage} from '../../config/api/index'
const app = getApp()
Page({
data: {
hasUserInfo: false,
openid:'',
imgUrls: [
'/image/img/1.jpg',
'/image/img/2.jpg',
'/image/img/3.jpg',
],
indicatorDots: true,
autoplay: true,
interval: 3000,
duration: 1000,
list:[],
status:0
},
//事件处理函数
bindViewTap: function() {
this.setData({
openid: app.globalData.openid
})
},
onLoad: function () {
this.getShowData()
},
// 条件查询 最近;狗;猫;其他
filter:function(e){
wx.showLoading({
title: 'loading...',
})
var that=this
var sort=e.currentTarget.id;
wx.request({
url: app.server +'/missingPet/showData',
data: {
sort:sort
},
success: function(res) {
// console.log(res.data)
that.setData({
list:res.data
})
wx.hideLoading();
},
fail: function(res) {},
})
},
getShowData:function(){
getPage().then(res=>{
// console.log(res.data)
this.setData({
list: res.data,
status: res.status
})
})
},
onReady:function(){
},
onShow:function(){
this.getShowData()
},
onPullDownRefresh:function(){
wx.showNavigationBarLoading()
getPage().then(res=>{
this.setData({
list: res.data,
status: res.status
})
wx.hideLoading()
wx.showToast({
title: '刷新成功',
image: '/image/success.png'
})
wx.hideNavigationBarLoading()
wx.stopPullDownRefresh();
})
}
})
可以正常请求接收数据了。