天天看点

微信小程序笔记——微信小程序request请求封装

一、前言

微信小程序提供的wx.request请求API,文档介绍的很清楚。直接使用代码未免累赘,并且处理一些返回操作不好统一处理,所以就对wx.request做了一下封装。

1.新建js文件(request => index.js)

微信小程序笔记——微信小程序request请求封装
// let baseUrl = 'http://******/'; //测试
// let baseUrl = 'http://******/';//预发布
let baseUrl = 'https://*****/';//线上
module.exports = function (url, method, data = {}) {
  let meth = method.toUpperCase()
  if (meth != "GET" && meth != "DELETE" && meth != "POST" && meth != "PUT") {
    meth = 'GET' //不传情况下默认'GET'
  }
  if(getApp().globalData.userInfo != null){//已登陆情况下必传参数(项目需要看情况而定)
    data['token'] = getApp().globalData.userInfo.token;
    data['uid'] = getApp().globalData.userInfo.uid;
  }
  return new Promise(function (resolve, reject) {
    wx.request({
      header:{
        'content-type': meth == 'POST' ? 'application/x-www-form-urlencoded' : 'application/json'
      },
      url: baseUrl + url,
      data: data,
      method: meth,
      success: function (res) {
        //返回信息统一处理操作

        //resolve用于具体调用中
        resolve(res)
      },
      fail: function (res) {
        //错误信息统一处理操作

        reject(res)
      }
    })
  })
}
           

2.js引用

import requestApi from '../../request/index.js' //引入

requestApi(your_request_url, 'POST', {
    union_id: id //参数
}).then((res) => {
    console.log(res)
}).catch((err)=>{
    console.log(res)
})