微信小程序请求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);
      // 可以在这里处理错误提示给用户
    }
  },
相关推荐
狂团商城小师妹41 分钟前
预约洗车小程序
微信小程序·小程序
future_studio1 小时前
聊聊 Unity(小白专享、C# 小程序 之 图片播放器)
unity·小程序·c#
Q_Q5110082855 小时前
python+uniapp基于微信小程序的心理咨询信息系统
spring boot·python·微信小程序·django·flask·uni-app·node.js
HuYi_code7 小时前
WeChat 小程序下载文件实现
微信小程序·uni-app
00后程序员张7 小时前
HTTPS 包 抓取与分析实战,从抓包到解密、故障定位与真机取证
网络协议·http·ios·小程序·https·uni-app·iphone
一匹电信狗8 小时前
【C++】C++风格的类型转换
服务器·开发语言·c++·leetcode·小程序·stl·visual studio
2501_915921438 小时前
iOS混淆与IPA加固实战手记,如何构建苹果应用防反编译体系
android·macos·ios·小程序·uni-app·cocoa·iphone
Q_Q51100828510 小时前
python+uniapp基于微信小程序的学院设备报修系统
spring boot·python·微信小程序·django·flask·uni-app
李慕婉学姐11 小时前
【开题答辩过程】以《自习室预约微信小程序》为例,不会开题答辩的可以进来看看
微信小程序·小程序
LB211211 小时前
苍穹外卖-购物车 前端修改(小程序主页与购物车模块显示不一致)
小程序