微信开发 封装全局request请求

这篇博客详细介绍了如何在微信小程序中进行全局的请求封装,包括在utils创建api.js文件,定义GET和POST请求方法,并在app.js中导入并覆盖原有的wx.request。此外,还展示了如何使用封装后的get和post方法获取接口数据,以及错误处理。通过这个教程,开发者可以更方便地在小程序中管理和调用API。
摘要由CSDN通过智能技术生成

微信开发 封装全局request请求

在utils 新建一个 api.js 文件

在这里插入图片描述

打开文件 封装请求

const app = getApp()

const bastUrl = 'https://api-hmugo-web.itheima.net/api/public/v1'
 

const Request = (url, options) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${bastUrl}${url}`,
      method: options.method,
      data:
        options.method === 'GET' ? options.data : JSON.stringify(options.data),
      header: {
        'Content-Type': 'application/json; charset=UTF-8',
      },
      success(request) {
       // 根据自己的接口写
        if (request.data.meta.status == 200) {
          resolve(request.data.message) 
        } else {
          reject(request.data.message)
        }
      },
      fail(error) {
        reject(error)
        console.log(error)
      },
    })
  })
}

const get = (url, options = {}) => {
  return Request(url, { method: 'GET', data: options })
}

const post = (url, options) => {
  return Request(url, { method: 'POST', data: options })
}

module.exports = {
  get,
  post,
}

打开 app.js 文件

import { get, post } from './utils/api'
App({
  onLaunch() {
    wx.get = (url, options) => {
      return get(url, options)
    }
    wx.post = (url, options) => {
      return post(url, options)
    }
  }
})


使用方法

  /**
   * 获取轮播图
   * @param {*} options
   */
  getSwiper() {
    wx.get('/home/swiperdata')
      .then((res) => {
        console.log(res)
      })
      .catch((err) => {
        console.log(err)
      })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getSwiper()
  },

接口文档示例

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ベ远行ミ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值