天天看点

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

配置文件

    新建配置文件 config/index.js

export default {
  /**
   * @description 连接请求地址
   */
  devServer: 'https://www.heyuhsuo.xyz/heyushuo'
}
           

    request封装文件 utils/request.js

/**
 * wx.request封装
 */
import config from '../config/index'
// 请求封装
function request (url, method, data, header = {}) {
  wx.showLoading({
    title: '加载中' // 数据请求前loading
  })
  return new Promise((resolve, reject) => {
    wx.request({
      url: config.devServer + url, // 仅为示例,并非真实的接口地址
      method: method,
      data: data,
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        wx.hideLoading()
        resolve(res.data)
      },
      fail: function (error) {
        wx.hideLoading()
        reject(error)
      },
      complete: function () {
        wx.hideLoading()
      }
    })
  })
}
export function get (url, data) {
  return request(url, 'GET', data)
}
export function post (url, data) {
  return request(url, 'POST', data)
}