微信小程序请求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);
      // 可以在这里处理错误提示给用户
    }
  },
相关推荐
黄华SJ520it1 天前
预约上门系统开发:懒人经济下的商业机遇与技术实践
小程序·系统开发
软件技术新观察1 天前
2026年北京教育医疗小程序与APP定制开发:十大服务商实力测评
大数据·小程序
万岳科技程序员小金1 天前
真人数字人小程序如何开发?AI数字人平台搭建流程全面解析
人工智能·小程序·ai数字人系统源码·ai数字人平台搭建·ai数字人小程序开发
didiplus2 天前
我在GitHub刷到一个诗词API,顺手写了款小程序
微信小程序
言乐62 天前
Python实现可运行解密游戏游戏框架
python·游戏·小程序·游戏程序·关卡设计
2501_915106322 天前
iOS 软件测试工具性能监控、日志分析 KeyMob、Instruments等
android·ios·小程序·https·uni-app·iphone·webview
云迈科技-软件定制开发2 天前
2026 AI智能体小程序APP开发怎么做:从场景规划到上线交付的完整参考
大数据·人工智能·小程序
小码哥0682 天前
医院陪诊小程序怎么开发-医院陪诊小程序源码功能-微信小程序 医院健康陪诊陪护系统
微信小程序·小程序·医院陪诊·陪诊系统·陪诊陪诊
书中枫叶3 天前
从「上次几点喂奶」到全栈小程序:我做了个喂宝助手
mongodb·微信小程序·node.js
黄华SJ520it3 天前
柯尔嫚商城模式开发:从概念到实现的完整指南
小程序·系统开发