微信小程序请求request封装

公共基础路径封装

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

请求封装

javascript 复制代码
// 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 || '网络请求失败');
      }
    });
  });
}

页面使用

javascript 复制代码
  async fetchData() {
    try {
      // 也可以点then
      const result = await request('/mini/default', 'get', {});
      console.log('请求成功,数据为:', result);
      // 处理数据,如设置到页面数据中
      this.setData({
        data: result
      });
    } catch (error) {
      console.error('请求失败:', error);
      // 可以在这里处理错误提示给用户
    }
  },
相关推荐
spmcor1 天前
微信小程序 setStorageSync 踩坑实录:别让"顺手一存"变成"隐形炸弹"
微信小程序
用户4324281061142 天前
小程序埋点设计规范:如何设计可扩展的数据采集体系
微信小程序
m0_526119402 天前
iconfont我修改好颜色,但是在小程序项目是黑色的
小程序
2601_956743682 天前
2026 上海小程序开发甄选:源码、云函数、跨端兼容技术评判
小程序·开发经验·上海
IT_张三2 天前
CSDN-项目分享-暑期备考小程序
小程序
IsJunJianXin3 天前
pdd小程序 cdp 保存响应体
linux·服务器·小程序·pdd小程序·拼多多响应体解密·小程序cdp·拼多多rpc取响应体
Geek_Vison3 天前
APP瘦身实战:从80MB+砍到15MB——基于小程序容器技术剥离APP非核心业务的实践分享
小程序·uni-app·mpaas
weikecms3 天前
聚合返利CPS小程序快速搭建教程
人工智能·微信·小程序
Haibakeji4 天前
长沙餐饮门店点餐配送小程序定制开发
大数据·小程序
2501_915918414 天前
iOS App性能测试工具的实现方法与优化循环指南
android·ios·小程序·https·uni-app·iphone·webview