0
点赞
收藏
分享

微信扫一扫

微信小程序 wx.request 请求封装

忍禁 2022-02-14 阅读 49

方式1:

const baseUrl = 'https://*****/';//这里可通过环境变量获取不同域名
// 封装请求
module.exports = function (options) {
  return new Promise((resolve, reject) => {
    wx.showLoading({
      title: '加载中',
    });
    wx.request({
      url: baseUrl + options.url,
      method:
        options.method === 'GET' ? options.data : JSON.stringify(options.data),
      data: options.data,
      header: {
        'content-type': 'application/json',
        // 'x-token': 'x-token'
      },
      success: function (res) {
        resolve(res);
        //这里可以加状态判断
      },
      fail: function (error) {
        reject(error);
      },
      complete: () => {
        setTimeout(() => {
          wx.hideLoading();
        }, 100);
      },
    });
  });
};

使用:

 //在其他页面使用 import request from '../utils/wxAjax'
 //进一步封装-1.js
  QUERY_USER_INFO(data = {}) {
        return request({
            // baseURL: hostConfig.xxx,
            url: "/api/user/info",
            method: "GET",
            data,
        });
    },
 //使用-2.js
 import { QUERY_USER_INFO } from 'xxx'
 
  QUERY_USER_INFO({a:1}).then(res => {
    if(){}
  }).catch(err => {
    wx.showToast({
        title: err.message,
    })
})
举报

相关推荐

0 条评论