微信小程序 wx.request请求封装
发布日期:2021-05-03 17:43:42 浏览次数:18 分类:精选文章

本文共 2253 字,大约阅读时间需要 7 分钟。

微信小程序 wx.request 请求封装

为了提升项目的可维护性,微信小程序的 wx.request 请求通常会进行封装。以下将详细讲解如何对 wx.request 请求进行封装。

一、创建 http.js 文件

首先,在项目中创建一个新的文件 http.js。这个文件将包含对 wx.request 请求的统一处理逻辑。

const apiHttp = 'https://***.****.com';
const socketHttp = 'https://***.****.com';
function fun(url, method, data, header) {
data = data || {};
header = header || {
'content-type': 'application/json'
};
const user_id = wx.getStorageSync('user_id');
if (user_id) {
data.user_id = user_id;
}
wx.showNavigationBarLoading();
wx.showLoading();
return new Promise((resolve, reject) => {
wx.request({
url: apiHttp + url,
header: header,
data: data,
method: method,
success(res) {
if (typeof res.data === "object") {
if (res.data.code) {
if (res.data.code === 410) {
console.log('请重新登录');
reject("请重新登录");
wx.redirectTo({
url: '../index/index'
});
}
}
}
},
fail() {
wx.redirectTo({
url: '../404/404'
});
},
complete() {
wx.hideNavigationBarLoading();
wx.hideLoading();
wx.stopPullDownRefresh();
}
});
});
}

二、在文件中添加请求类型处理

http.js 文件进行扩展,添加对不同请求类型的支持:

module.exports = {
apiHttp: apiHttp,
socketHttp: socketHttp,
get: function(url, data, header) {
return fun(url, 'GET', data, header);
},
post: function(url, data, header) {
return fun(url, 'POST', data, header);
}
};

三、在页面中引用封装好的函数

在需要使用 wx.request 的页面中引入封装后的函数:

const $http = require('../../utils/http.js');
// 示例使用
request_index_info: function() {
const $this = this;
$http.post('index/index', {})
.then(res => {
// 处理成功回调
})
.catch(err => {
console.log('请求失败', err);
});
};

以上就是对 wx.request 请求的封装实现方法。通过将通用请求逻辑抽象到 http.js 文件中,可以显著提升代码的可维护性,同时在页面中仅需简单地调用封装后的函数即可完成各种网络请求。

上一篇:微信小程序如何利用 canvas一键生成海报并保存到本地?纯前端完成
下一篇:微信小程序登陆组件封装

发表评论

最新留言

表示我来过!
[***.240.166.169]2025年04月09日 04时54分26秒