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

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)
    });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值