【微信小程序】网络请求封装 使用Promise 封装 wx.request

创建httpServire.js 统一请求模板

const app = getApp();
// 线上
const URL_HOST = 'https://betadoctor.taiorient.com/api/';
let header = {
  "content-type": "application/json;charset=UTF-8"
}
const formatParams = (data) => {
  let arr = [];
  for (let name in data) {
    arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
  }
  return arr.join("&");
}
// 请求封装
export const httpService = (urlEnd, params, method) => {
  return new Promise((resolve, reject) => {
    let url = '', data = ''
    if (method == 'post') { 
      url = URL_HOST + urlEnd
      data = params
    } else if (method == 'get') { 
      url = URL_HOST + urlEnd + '?' + formatParams(params)
      data = undefined
    }
    wx.request({
      url,
      data,
      method,
      header: header,
      timeout: 15000,
      success: res => {
        if ( res.data.code == 200 ) {
          resolve(res.data)
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
          reject(res)
        }
      },
      fail: error => {
        wx.showToast({
          title: error.errMsg,
          icon: 'none',
          duration: 2000
        })
        reject(error)
      },
    })
  })
}

创建对应模块的api

const { httpService } = require("./httpServire.js");
export const myHomePage = params => {
  return httpService("applet/user/myHomePage", params, "get");
};

页面调用

const { myHomePage } = require("../../utils/api.js")
async myHomePagePort() {
    let data = {}
    const getData = await myHomePage(data)
    console.log(getData)
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值