1. 网络请求封装的意义
在小程序开发中,频繁地与后端API交互是不可避免的。微信平台提供了基础的网络接口(wx.request)和上传下载接口,但直接使用这些原生接口会导致代码重复、难以维护。通过封装网络请求,可以实现代码复用、统一管理和错误处理,提升开发效率和代码质量。
2. 创建网络请求封装文件
在项目中创建一个.js文件(如http.js),用于集中管理网络请求。在这个文件中,我们可以对wx.request进行封装,设置统一的配置项,例如:
const request = (url, method, data) => {
return new Promise((resolve, reject) => {
wx.request({
url: url,
method: method,
data: data,
timeout: 3000, // 设置超时时间为3秒
header: {
'Content-Type': 'application/json' // 使用JSON格式提交数据
},
success(res) {
resolve(res.data)
fail(err) {
reject(err)
})
})
}
3. 定义GET请求方法
GET请求通常用于从服务器获取数据。在封装文件中添加一个专门的get方法:
export const get = (url, data = {}) => {
return request(url, 'GET', data)
}
使用示例:
const http = ({
url = "",
param = {},
...other
} = {}) => {
// wx.showLoading({
// title: "网络请求中..",
// });
let timeStart = Date.now();
let cookie = wx.getStorageSync("sessionKey");
return new Promise((resolve, reject) => {
wx.request({
url: url,
data: param,
header: {
"content-type": "application/json", // 默认值
Cookie: cookie,
},
...other,
timeout: 3000,
complete: (res) => {
// wx.hideLoading();
console.log(`耗时${Date.now() - timeStart}`);
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve(res);
} else {
reject(res);
}
},
});
});
};
get('https://api.example.com/data').then(res => {
console.log(res)
}).catch(err => {
console.error(err)
})
4. 定义POST请求方法
POST请求通常用于向服务器提交数据。同样地,我们可以封装一个post方法:
export const post = (url, data = {}) => {
return request(url, 'POST', data)
}
使用示例:
post('https://api.example.com/submit', {name: 'John'}).then(res => {
console.log(res)
}).catch(err => {
console.error(err)
})
5. 异常处理的重要性
// get方法
function httpGet(url, param = {}) {
return http({
url: getUrl(url),
param,
});
}
在实际开发中,网络请求可能会因为各种原因失败,例如网络不可用、服务器错误或请求超时。如果不进行适当的异常处理,可能会导致用户体验问题。
用户在小程序启动时遇到网络问题
请求一直处于加载状态,UI显示"加载中"但不结束
某些API调用失败导致后续流程中断
改进方案:
get('https://api.example.com/data').then(res => {
// 处理成功响应
}).catch(err => {
// 统一处理错误
wx.showToast({
title: '网络请求失败',
icon: 'none'
})
// 记录错误日志
console.error('请求失败:', err)
}).finally(() => {
// 无论成功与否都隐藏加载状态
wx.hideLoading()
})
6. 实际应用示例:获取IP地址
function httpPost(url, param = {}) {
return http({
url: getUrl(url),
param,
method: "post",
});
}
以下是一个完整的获取IP地址的示例,展示了如何使用封装好的网络请求:
// 在页面中调用
wx.showLoading({title: '加载中'})
get('https://api.ipify.org?format=json').then(res => {
console.log('当前IP地址:', res.ip)
this.setData({ip: res.ip})
}).catch(err => {
console.error('获取IP失败:', err)
wx.showToast({
title: '获取IP失败',
icon: 'none'
})
}).finally(() => {
wx.hideLoading()
})
7. 最佳实践建议
1. 将网络请求封装放在项目公共目录中
2. 为不同业务模块创建单独的API文件
3. 统一处理错误和加载状态
4. 设置合理的超时时间(如3秒)
5. 在开发阶段记录详细的请求日志
6. 考虑添加请求重试机制
7. 对敏感数据进行加密处理
通过合理的网络请求封装,可以显著提升小程序开发效率和稳定性,为用户提供更好的使用体验。
doQueryIP: function () {
const that = this;
wx.showLoading({
title: '加载中...',
mask: true,
})
ohttp.httpGet('/pubip').then((res) => {
if (res.data.code == 1) {
const rdata = res.data.data;
const ip = rdata.trim().split(" ")[0];
that.setData({
rdata: rdata,
ip:ip,
})
wx.hideLoading({
success: (res) => { },
})
wx.showToast({
title: '查询成功',
})
} else {
wx.hideLoading({
success: (res) => { },
})
wx.showToast({
title: '请稍后再试',
})
}
}).catch((err)=>{
console.log(err);
wx.hideLoading({
success: (res) => { },
})
})
},
版权声明:本文为 “博览广文网” 原创文章,转载请附上原文出处链接及本声明;
工作时间:8:00-18:00
客服电话
0755-88186625
电子邮件
admin@lanyu.com
扫码二维码
获取最新动态