微信小程序请求封装及使用(赞!)

app.js

//app.js
App({

  onLaunch: function() {
    let _self = this;
    wx.getSystemInfo({
      success: res => {
        let modelmes = res.model;
        if (modelmes.search('iPhone X') != -1 || modelmes.search('iPhone 11') != -1) {
          _self.globalData.isIphoneX = true
        }
        // wx.setStorageSync('modelmes', modelmes)
      }
    })
  },
  // dev: 开发测试环境
  // prod: 生产环境
  // env: 'dev',
  globalData: {
    userInfo: null,
    amap: '',
    key: ''
  },
  httpErr(msg) {
    wx.showToast({
      title: msg || '系统出小差了',
      icon: 'none',
      duration: 1500
    })
  }
})

在utils文件夹下新建url.js文件

const { hexMD5 } = require('./md5.js');
const { jsonSort } = require('./sortJson.js');
const app = getApp()
// const HOST_URL = app.env === 'dev' ? '接口地址' : '';
const HOST_URL = '接口地址';
const MD5_KEY = 'MD5_KEY 找后台要';
/**
 * method: 请求类型 get ,post
 * url: 接口地址
 * data: 请求数据
 * 
*/
const fetchData = (method, url, data, openId = wx.getStorageSync('openId')) => {
  return new Promise((resolve, reject) => {
    const httpMethod = ['get', 'GET', 'post', 'POST'];
    if (httpMethod.indexOf(method) == -1) {
      app.httpErr('请求类型仅支持get和post');
      reject('请求类型仅支持get和post');
      return;
    }
    if (!url) {
      app.httpErr('请求地址错误');
      reject('请求地址错误');
      return;
    }
    wx.showLoading({
      title: '加载中',
    })
    let commonData = {
      distributorId: '1007',// 渠道id 1007为微信
      // 时间戳
      timeStamp: Math.round(new Date().getTime() / 1000),
    }
    // if (url != '/userInfo/queryUserInfo') {
    //   commonData.openId = openId;
    // }
    console.log(jsonSort(commonData))
    commonData.hmac = hexMD5(jsonSort(commonData) + MD5_KEY).toUpperCase();
    let postData = Object.assign(commonData, data);
    wx.request({
      method: method,
      url: HOST_URL + url, //仅为示例,并非真实的接口地址
      data: postData,
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: res => {
        console.log(res)
        wx.hideLoading();
        if (res.data.code === '0000') {
          resolve(res.data.data);
        } else {
          app.httpErr(res.data.message);
          reject(res.data.message || '系统出小差了');
        }
      },
      fail: err => {
        wx.hideLoading();
        app.httpErr();
        reject(err);
      }
    })
  })
}


exports.HOST_URL = HOST_URL;
exports.fetchData = fetchData;

使用

const app = getApp();
const {
  HOST_URL,
  fetchData
} = require('../../utils/url.js');
let httpFlag = false; // 正在发送请求?

let data = {
	userName: 'hh'
}

fetchData('post', '接口路径', data).then(res => {
      console.log(res);
      
    }).catch(err => {
      console.error(err)
    });

你可能感兴趣的:(微信小程序请求封装及使用(赞!))