玄机随录小程序微信小程序学习

使用Promise封装微信request请求

2020-01-03  本文已影响0人  编程小橙子
timg.jpg

2020到来了,首先祝大家新年快乐

直接看代码

在开发工具的utils->util.js中封装wx.request请求

utils/util.js

GET

/**
 * 封装request请求
 */
/**
 * GET
 */
function appGet(url, data = {}, method = 'GET') {
  return new Promise((resolve, reject) => {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
      },
      success: res => {
        if (res.statusCode == 200) {
          resolve(res.data)
        } else {
          reject(res.errMsg)
        }
      }
    })
  })
}

POST

/**
 * POST
 */
function appPost(url, data = {}, method = 'POST') {
  return new Promise((resolve, reject) => {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
      },
      success: res => {
        if (res.statusCode == 200) {
          resolve(res.data)
        } else {
          reject(res.errMsg)
        }
      }
    })
  })
}

注意:一定要记得导出模块

module.exports = {
  appGet,
  appPost
}

请求地址全部放在config->api.js脚本中,注:config文件和pages是同级

config/api.js

// api地址
var WxApiUrl = 'xxx';
module.exports = {
  IndexUrl: `${WxApiUrl}home/index`, //首页数据加载
}

最后进入pages/index/index.js下使用封装好的方法

pages/index/index.js

//index.js
const util = require('../../utils/util.js');
const api = require('../../config/api.js');
Page({
  data: {

  },
  onLoad: function() {
    util.appGet(api.IndexUrl).then(res => {
      console.log(res.data)  //可以获取到数据
      console.table(res)  //表格方式展示数据更清晰
    })
  },
})
image.png

本次分享的内容就到这里,喜欢的小伙伴欢迎关注支持,后续会带来更多精彩

上一篇下一篇

猜你喜欢

热点阅读