本站资源是站长搜集整理而成,版权均归原作者所有,若无意中侵犯到您的版权利益,请来信联系我们删除! 本站所有资源只用于研究学习,不得作为商业用途、非法谋取暴利,否则,一切后果均由自己承担!

首页 > 教程

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

  • slbcun
  • 2025-04-07
  • 1033 ℃

调用方法

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)

    • 这篇文章还没有收到评论,赶紧来抢沙发吧~


Top