小程序封装request

  • 目前小程序只支持 es6 及以下编译, 只能用 Promise 封装了
  • 在 utils 文件新建 request.js
//基地址
const BASE_URL = 'https://xxx'
const request = (url, options, noLoading, header) => {
  return new Promise((resolve, reject) => {
//全局加载 showLoading
    if (!noLoading) {
      wx.showLoading({
        title: '努力加载中...', // 提示的内容,
        mask: true // 显示透明蒙层,防止触摸穿透,
      })
    }
  
    wx.request({
      url: BASE_URL + url,
      method: options.method, //配置method方法
      data:  options.data,
      header: {
        'Content-Type': options.method === 'GET' ? 'application/json; charset=UTF-8': 'application/x-www-form-urlencoded',
      }, //header中可以添加token值等
          //content-type’: ‘application/x-www-form-urlencoded’ 请求参数自然就变成了form-data形式
      success(request) { //监听成功后的操作
        if (request.statusCode === 200) {
          resolve(request.data)
        } else {
          reject(request.data)
          wx.showToast({
            title: `[ ${res.statusCode} ]${res.errMsg} `, // 提示的内容,
            icon: 'none', // 图标,
            duration: 2000, // 延迟时间,
            mask: true, // 显示透明蒙层,防止触摸穿透,
           success: res => {}
          })
        }
      },
      fail(error) { //返回失败也同样传入reject()方法
        reject(error.data)
        console.log(error);
          wx.showToast({
            title: `[ ${error.errMsg} ] `, // 提示的内容,
            icon: 'none', // 图标,
            duration: 2000, // 延迟时间,
            mask: true, // 显示透明蒙层,防止触摸穿透,
            success: res => {}
          })
      },
      complete() {
        wx.hideLoading()
      }
    })
  })
}

//封装get方法
const get = (url, options = {},noLoading) => {
  return request(url, {
    method: 'GET',
    data: options,
  },
  noLoading
  )
}

//封装post方法
const post = (url, options = {},noLoading,) => {
  return request(url, {
    method: 'POST',
    data: options,
  },noLoading,)
}

//封装put方法
const put = (url, options) => {
  return request(url, {
    method: 'PUT',
    data: options
  })
}
//封装remove方法,DELETE关键字不能声明
const remove = (url, options = {}) => {
  return request(url, {
    method: 'DELETE',
    data: options
  })
}

module.exports = {
  get,
  post,
  put,
  remove
}
  • 全局使用可以挂载到 app 上
import $request from './utils/request.js'
App({
  onLaunch: function () {

  },
  $request,
  globalData: {
    userInfo: null,
    
  },
  
})

  • 或者调用 api.js 使用
import request from './request';
module.exports = {
  /**
   * 是否为会员
   * @param userId: 用户ID
   */
  isMenberShipOuery: (userId) => {
    return request.get('/xxx/xxx', {
      userId: userId
    });
  },

};

  • 页面调用api
const api = require('../../utils/api');

      api.isMenberShipOuery(userId).then((rep => {
        if (rep.isMembership === 1) {
          // 会员
          wx.navigateTo({
            url: '/pages/novice/novice?phoneNumber=' + phoneNumber
          })
        } 
      }));
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。