微信小程序原生wx.request简单封装(自用版)

微信小程序原生wx.request简单封装(自用版)

韩小韩
2022-06-23 / 5 评论 / 1,523 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年06月23日,已超过674天没有更新,若内容或图片失效,请留言反馈。

调用方法

import {
  get,post
} from '../../request/request'

// GET请求
const _res = await get('https://api.vvhan.com/api/ian')
console.log(_res)
// POST请求
const _res = await post('https://api.vvhan.com/api/ian')
console.log(_res)

request.js

const request = (url, options) => {
  return new Promise((resolve) => {
    options.isLoading && wx.showLoading({
      title: '正在加载',
    })
    wx.request({
      url,
      method: options.method,
      data: options.data,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      success(res) {
        resolve(res.data)
        options.isLoading && wx.hideLoading();
      },
      fail(error) {
        options.isLoading && wx.hideLoading();
        wx.showToast({
          icon: 'none',
          title: '请求失败',
          duration: 1400
        });
      }
    })
  })
}

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

const post = (url, options = {}, isLoading = true) => {
  return request(url, {
    method: 'POST',
    data: options,
    isLoading
  })
}
module.exports = {
  get,
  post,
}
0

评论 (5)

取消
  1. 头像
    Net
    Windows 7 Windows 7 / Microsoft Edge Microsoft Edge 中国北京市新国信通信有限公司

    不知道怎么弄,好专业。

    回复
    1. 头像
      韩小韩 作者
      Windows 10 Windows 10 / Google Chrome Google Chrome 中国江苏省南京市电信
      @ Net

      表情

      回复
  2. 头像
    vian
    Windows 10 Windows 10 / Google Chrome Google Chrome 中国广东省深圳市电信

    进公司的时候公司的微信小程序就做好了

    回复
    1. 头像
      韩小韩 作者
      Windows 10 Windows 10 / Google Chrome Google Chrome 中国江苏省南京市电信
      @ vian

      别人的总归是别人的

      回复
      1. 头像
        vian
        Windows 10 Windows 10 / Google Chrome Google Chrome 中国广东省深圳市电信
        @ 韩小韩

        不假 别人的总归的别人的

        回复