微信小程序请求request封装

作者 : admin 本文共1190个字,预计阅读时间需要3分钟 发布时间: 2024-06-16 共3人阅读

公共基础路径封装

微信小程序请求request封装插图

// config.js
module.exports = {
  // 测试
  BASE_URL: 'https://cloud.chejj.cn',
  // 正式
  // BASE_URL: 'https://cloud.mycjj.com'
};

请求封装

微信小程序请求request封装插图(1)

// request.js
import config from '../config/baseUrl'
// 请求未返回时的loading
const showLoading = () => wx.showLoading({
title: '加载中...'
});
const hideLoading = () => wx.hideLoading();
// 封装的请求函数
export function request(url, method = 'GET', data = {}) {
let fullUrl = config.BASE_URL + url;
return new Promise((resolve, reject) => {
showLoading(); // 显示加载提示
wx.request({
url: fullUrl,
method: method,
data: data,
header: {
'content-type': 'application/json', // 默认值
// 'Authorization': 'Bearer ' + token
// 'Bearer '是一个常见的前缀,表示你使用的认证方案是Bearer Token,这是OAuth 2.0中常用的认证方式。如果你的API要求或允许不同的认证方案,那么前缀应做相应调整或省略。
},
success: (res) => {
if (res.statusCode === 200 && res.data.success) {
hideLoading(); // 请求成功后隐藏加载提示
resolve(res.data.data); // 返回实际数据部分
} else {
hideLoading(); // 即便请求失败,也要隐藏加载提示
// 错误提示
wx.showToast({
title: res.data.msg,
icon: 'error'
})
reject(res.data.msg || '请求失败'); // 错误处理
}
},
fail: (err) => {
hideLoading(); // 失败时隐藏加载提示
reject(err.errMsg || '网络请求失败');
}
});
});
}

页面使用

  async fetchData() {
try {
// 也可以点then
const result = await request('/mini/default', 'get', {});
console.log('请求成功,数据为:', result);
// 处理数据,如设置到页面数据中
this.setData({
data: result
});
} catch (error) {
console.error('请求失败:', error);
// 可以在这里处理错误提示给用户
}
},
本站无任何商业行为
个人在线分享 » 微信小程序请求request封装
E-->