「这是我参与2022首次更文挑战的第25天,活动详情查看:2022首次更文挑战」。
在小程序开发中,request请求方式的封装是必不可少的,可以给我们带来很大的便利。常用的有3种方式,get请求,post body请求,post param请求,我们一起看看吧!
request请求封装
将接口地址(url),请求参数(data),请求方式(method)和isPostParam(是否是post param请求)作为参数传入
- 其中header(头部信息)需要封装一下。这是因为我们一般将登录的token信息放在header中,而登录接口不需要token,所以需要在header中根据调用的url做判断。
- 接口返回状态码是203的时候是登录过期,需要跳转到登录页面。并删除token信息。
- 当请求方式是postParam的时候,传参为true。因为postParam的请求传参和其他方式不一样,特殊处理。 封装的requst的js代码如下:
const request = (url, data, method, isPostParam) => {
return new Promise((resolve, reject) => {
showFullScreenLoading();
let serverUrl = `${url}`
if (data && isPostParam) {
serverUrl += QS.stringify(data, {
addQueryPrefix: true,
allowDots: true,
})
}
wx.request({
url: serverUrl,
data: data,
method: method,
header: getHeader(url),
success: (res) => {
if (res.data.status == 200) {
setHeader(res.header.Authorization);
resolve(res.data.result);
} else {
wx.showToast({
title: res.data.message,
icon: 'none',
duration: 2000
})
// 登录过期
if (res.data.status == 203) {
wx.reLaunch({
url: '/pages/login/login',
})
wx.removeStorage({key: 'authorization'});
}
}
},
fail: (res) => {
// HTTP 状态码
if (res.statusCode == 501) {
wx.showToast({
title: '网络出小差了,请重试',
icon: 'none'
})
}
reject();
},
complete: (res) => {
hideFullScreenLoading();
},
})
})
}
一般在请求接口的时候需要展示一个loading图标,而在每一个方法中写又太累赘,可以在封装方法的时候统一调用,简化代码。
// loading配置,请求次数统计
function startLoading() {
t = setTimeout(() => {
wx.showLoading({
title: '加载中...',
mask: true
})
hasLoading = true;
}, 200);
}
function endLoading() {
wx.hideLoading();
}
有时候不是一次只请求一个接口,而是同时请求好多个接口,这时候loading会一直出现。我们常常不需要这样,我们希望他只展示一次,这个时候需要统计接口数量,来展示loading。
// 声明一个对象用于存储请求个数
var needLoadingRequestCount = 0;
function showFullScreenLoading() {
if (needLoadingRequestCount === 0) {
startLoading();
}
needLoadingRequestCount++;
};
function hideFullScreenLoading() {
if (needLoadingRequestCount <= 0) return;
needLoadingRequestCount--;
if (needLoadingRequestCount === 0) {
clearTimeout(t);
if (hasLoading) {
endLoading();
hasLoading = false
}
}
};
设置请求header信息
// 设置请求header信息
const getHeader = (url) => {
if (url.indexOf(api.wxLogin) > -1 || url.indexOf(api.registerLogin) > -1) {
return;
} else {
return {
'content-type': 'application/json',
'authorization': wx.getStorageSync('authorization'),
'isPc': 0,
}
}
}
// 设置response header信息
const setHeader = (token) => {
wx.setStorageSync('authorization', token);
getApp().globalData.authorization = token;
}
以上就是在小程序中封装request的请求了,希望怼你有帮助!