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

调用方法

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,
}

相关文章

显卡天梯图2024最新版,显卡是电脑进行图形处理的重要设备,...
初始化电脑时出现问题怎么办,可以使用win系统的安装介质,连...
todesk远程开机怎么设置,两台电脑要在同一局域网内,然后需...
油猴谷歌插件怎么安装,可以通过谷歌应用商店进行安装,需要...
虚拟内存这个名词想必很多人都听说过,我们在使用电脑的时候...