Implement a network request (with and without token access apis)

request.js

### Whether the encapsulation request automatically carries the token

const API_BASE_URL = 'https://***.com';

const REQUEST = (url, method, data = {}) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: API_BASE_URL + url,
      method: method,
      data: data,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success(res) {
        resolve(res.data)
      },
      fail(error) {
        reject(error)
      }
    })
  })
}

const HTTP = (url, method, data, isToken = true) = > {###isToken specifies whether the request will automatically carry a token value. Default is true
  return new Promise((resolve, reject) => {
    if (isToken) { Request with token
      let token = wx.getStorageSync('token')
      if (token) { ### cache has tokens directly used
        data = Object.assign({
          openId: token
        }, data)
        REQUEST(url, method, data).then(res => {
          resolve(res)
        })
      } else { ### Cache does not have token, use code in exchange
        wx.login({
          success: res => {
            if (res.code) {
              getUserAuthor({
                code: res.code
              }).then(res => {
                wx.setStorageSync('token', res.data.openid)
                data = Object.assign({
                  openId: res.data.openid
                }, data)
                REQUEST(url, method, data).then(res => {
                  resolve(res)
                })
              })
            }
          }
        })
      }
    } else { ### Request without token
      REQUEST(url, method, data).then(res => {
        resolve(res)
      })
    }
  })
}

let getUserAuthor = (code) => {
  return REQUEST('/auth/getUserAuthor'.'get', code)
}

let getGoldCount = (data) => {
  return HTTP('/mini/user/getGoldCount'.'get', data, true)}let getGoods = (data) => {
  return HTTP('/goods/getGoods'.'get', data, false)}export default {
  getGoldCount: getGoldCount,
  getGoods: getGoods
}

Copy the code

Index.js (calling page)

import HTTP from '.. /.. /utils/request';
Page({
  data: {

  },
  
  onLoad: function (options) {
    const goodsId = '040e5a34-43c2-4f19-b1a0-a5d157f15062';
    this.getGoldCount();
    this.getGoods({ goodsId: goodsId});
  },
  
  getGoldCount() {
    HTTP.getGoldCount().then((res) => {})
  },
  
  getGoods(data){
    HTTP.getGoods(data).then((res) => {})
  }
})

Copy the code